Satisfied Symfony doctrine and then map
Basically, I want to execute this mysql query with the doctrine:
select distinct user_id from work_hour where project_id = ?;
But I don't know how to do it with pretty Doctrine code. Can I make it look like the following pseudocode or do I need to use a query builder ?:
$project = new Project();
...
$entities = $em->getRepository('AppBundle:WorkHour')
->findByProject($project)->selectUser()->distinct();
Where $ objects is an array of User objects
WorkHour and Project have a ManyToOne relationship
WorkHour and User have a ManyToOne relationship
source to share
To do this, you need to use , but it will still be pretty "pretty Doctrine code" and still look like your pseudocode.
Something like this should work: QueryBuilder
$queryBuilder = $em->createQueryBuilder();
$query = queryBuilder
->select('u')
->distinct()
->from('AppBundle:User', 'u')
->join('AppBundle:WorkHour', 'wh')
->where('u.workHour = wh')
->andWhere('wh.project = :project')
->getQuery();
$query->setParameter(':project', $project);
$entities = $query->getResult();
source to share
public function findByProject($project)
{
$qb = $this->getEntityManager()->createQueryBuilder('User');
$qb
->select('User')
->from('Path\Bundle\Entity\User', 'User')
->join('Path\Bundle\Entity\WorkHour', 'wh',
'WITH', 'User.workHour = wh')
->where('wh.project = :project'))
->distinct()
->setParameter('project', $project)
;
$query = $qb->getQuery();
return $query->getResult();
}
If you have a complex query, you must do it in a QueryBuilder, it will be more efficient.
http://doctrine-orm.readthedocs.org/en/latest/reference/query-builder.html
If you have complex queries, you shouldn't do it directly in the controller, it shouldn't know this logic, you should do it in the repository and call it from there
source to share