Home > OS >  Symfony Many-to-many query
Symfony Many-to-many query

Time:10-06

I have a question about Symfony's Many-to-many relationships. I have a query, that tries to get all the fields of an entity (outside this part), and on top of that query, it adds the following:

 $queryBuilder
            ->leftJoin('AppBundle:Location', 'location',
                Join::WITH, 'location.id IN (entity.locations)')
            ->andWhere('location.institute=:institute')
            ->setParameter('institute', $user->getInstitute());

On that entity, a Many-to-many relationship is present: entity has a m2m relationship with location. Now I try to get all entities that have the same institute as the user has. So I query the locations, and check if the institute of the locations have the same institute.

However, I then get

[Syntax Error] line 0, col 118: Error: Expected Literal, got 'entity'

What should I be doing different? I understand it goes wrong with the IN part of the query.

CodePudding user response:

I think your entity.locations is a variable.

If so, you need to add : in front of and setParameter as well.

Change your code to:

$queryBuilder
  ->leftJoin('AppBundle:Location', 'location', Join::WITH, 'location.id IN (:locations)')
  ->setParameter('locations', entity.locations);
  ->andWhere('location.institute=:institute')
  ->setParameter('institute', $user->getInstitute());

Please let me know if this solve your issue, thanks!

CodePudding user response:

In the end, I found out that the answer is as follows:

 $queryBuilder
        ->leftJoin('AppBundle:Location', 'location',
            Join::WITH, 'location MEMBER OF entity.locations')
        ->andWhere('location.institute=:institute')
        ->setParameter('institute', $user->getInstitute());
  • Related