简体   繁体   中英

Doctrine Query Builder Result: not looping correctly

I'm not sure if it's that I'm not doing correctly but this is giving me an error:

I have 2 Entities: Task and TaskUser. They are connected by a onetoMany.

What I want to do is this:

foreach($tasks as $task){
echo $task->getTitle;
echo $task->getTaskUser()->getFirstName();
}

This is my query in the Task Repository:

    public function findTasksByUsers($user = false)
{

    if($user){

    $qb = $this->_em->createQueryBuilder();

    $qb
    ->select('t', 'tu')
    ->from('\Entities\Task', 't')
    ->leftJoin('\Entities\TaskUser', 'tu',  \Doctrine\ORM\Query\Expr\Join::WITH, 't.id = tu.task')
    ->where('tu = :user')
    ->setParameter('user', $user)
    ->orderBy('t.createDate', 'DESC');

    return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT);

    }

}

When I do this loop:

$tasks = $this->em->getRepository('\Entities\Task')->findTasksByUsers($user);

foreach($tasks as $task){
        echo $task->getTitle();
    }

I get the the title of the first task, and then an error like this:

Title of first task
Fatal error: Call to undefined method Entities\TaskUser::getTitle() in D:\sites\db\application\controllers\TasksController.php on line 35

Any idea why this is happening? Thanks!

$qb->select('t', 'tu')

the issue is here as you're selecting both entities.

If you want only Task entity modify your DQL as follows

$qb->select('t')

However, to me, you could only procede that way (in your controller; if you aren't into controller, use DI to access entity manager)

//retrieve all TaskUser object
$em = $this->getDoctrine()->getManager();
$tu_repo = $em->getRepository('YourBundleName:TaskUser');
$tu_array_collection = $tu_repo->findBy(array('user'=>$user));
foreach ($tu_array_collection as $tu) {
  $first_name = $tu->getFirstName();
  foreach ($tu->getTasks() as $task) {
    echo $first_name;
    echo $task->getTitle();
  }
}

of course you may need to adapt your code with right findBy array, and with correct methods from TaskUser entity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM