Brian
Brian

Reputation: 7135

Symfony / Doctrine: Limit query based on association ID without loading association or joining it

Let's say I have a many-to-one relationship involving a Person entity and a Position entity. The foreign key lives on the Person entity. I want to write a query that limits results to people of a specific position without having to join the Position association to the query or loading the Position entity.

$qb = $em->createQueryBuilder()
  ->select('Person')
  ->from('AcmeBundle:Person', 'Person')
  ->where('Person.position_id = :position_id')
  ->setParameter('position_id', 1)
;

This doesn't work, because there is no position_id property on the Person entity. Instead, I'd have to first join the Position association and do this:

$qb = $em->createQueryBuilder()
  ->select('Person')
  ->from('AcmeBundle:Person', 'Person')
  ->join('Person.position', 'Position')
  ->where('Position.id = :position_id')
  ->setParameter('position_id', 1)
;

or this:

$qb = $em->createQueryBuilder()
  ->select('Person')
  ->from('AcmeBundle:Person', 'Person')
  ->where('Person.position = :position')
  ->setParameter('position', $loaded_position_object)
;

Is it possible to limit my query by ID of Position without (1) joining the Position association or (2) loading the full position object?

Upvotes: 0

Views: 318

Answers (1)

costa
costa

Reputation: 1087

Instead this

...
->where('Person.position_id = :position_id')
...

you should do it like this

...
->where('Person.position = :position_id')
...

Upvotes: 1

Related Questions