我正在构建一个简单的任务规划器。这是来自TaskController.php文件的片段。如何将这3个查询(任务,未完成,已完成)组合起来使其工作?我应该使用DQL吗?
/**
* Lists all task entities.
*
* @Route("/", name="task_index")
* @Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$tasks = $em->getRepository('TaskBundle:Task')->findByUser($this->getUser()); // all tasks of a specific user
$notcompleted = $em->getRepository('TaskBundle:Task')->findByCompleted(false); //tasks that are not completed
$completed = $em->getRepository('TaskBundle:Task')->findByCompleted(true); // all completed tasks
return $this->render('task/index.html.twig', array(
'notcompleted' => $notcompleted,
'completed' => $completed,
'tasks' => $tasks,
));
}
答案 0 :(得分:3)
您可以使用Doctrine的\Doctrine\Common\Collections\Collection::partition()
分割任务:
$em = $this->getDoctrine()->getManager();
$tasks = $em->getRepository('TaskBundle:Task')->findByUser($this->getUser());
$collection = new ArrayCollection($tasks);
list($completed, $notcompleted) = $collection->partition(function ($key, Task $task) {
return $task->isCompleted();
});
return $this->render('task/index.html.twig', array(
'notcompleted' => $notcompleted,
'completed' => $completed,
'tasks' => $tasks,
));
答案 1 :(得分:0)
最简单的解决方案可能是过滤控制器中的任务:
$em = $this->getDoctrine()->getManager();
$tasks = $em->getRepository('TaskBundle:Task')->findByUser($this->getUser());
$notcompleted = $completed = [];
foreach ($tasks as $task) {
if ($task->isCompleted()) {
$completed[] = $tasK;
} else {
$notcompleted[] = $task;
}
}
return $this->render('task/index.html.twig', array(
'notcompleted' => $notcompleted,
'completed' => $completed,
'tasks' => $tasks,
));
在此解决方案中,您只进行一次数据库查询,而不是三次查询。