Home > Mobile >  How can I join two tables without association?
How can I join two tables without association?

Time:11-19

I try to combine two arrays in Symfony that do not have an association field. In documents the field "uuid" is actually the "documentId" in data. Here my approach:

$builder = $this->em->createQueryBuilder();
           $result = $builder->select('documents')
              ->from('App:Documents', 'documents')
              ->leftJoin('data', 'data')
              ->andWhere('documents.uuid = data.documentId')
              ->andWhere('data.fields = :id')
              ->setParameter('id', 2)
              ->getQuery()
              ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

But I get the error message that documents has no association data.

CodePudding user response:

You are quite close, but lack a few things.

You need to be more precise with your join and specify which entity is targeted (if there is no relation or inheritance).

// If your entity name is called Data
->leftJoin(Data::class, 'data', 'WITH','data.documentId = documents.uuid')

Let's say you are creating your method from the Documents repository (which by the way should be in singular instead of plural).

Your method would look like this:

$result = $this->createQueryBuilder('documents')
    ->select('documents as document, data as myData')
    ->leftJoin(Data::class, 'data', \Doctrine\ORM\Query\Expr\Join::WITH,'data.documentId = documents.uuid')
    ->getQuery()
    ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

But I think there may be an issue with your schema if there is no relation between two entities that are clearly related.

  • Related