I’m working with Symfony2.
I have an entity Employee and an entity Message related by an OneToMany association.
So a employee can have some messages and I want to have the one which has been sent the most recently, for a given employee.
Is this query correct ?
<?php
public function getLast($id_employee)
{
$query = $this->_em->createQuery(
'SELECT MAX(m.sentAt) FROM MyBundle:Message m JOIN m.employee e
WHERE e.id = ' . $id_employee);
return $query->getSingleResult();
}
Thanks a lot
You haven’t need to do a
JOINsince the external key is alredy onto yourmessagetable and since we can think that a message belongs only to one user and one user can have multiple messages related to him.So your query will be
and you have to modify your code in that way
However if you had to do a join, please remember this important things
ONcondition is about keys, you haven’t to specify it withWHEREclauseDQL(or use it only a little) and use something like->leftJoin(..),->where(..)and so on