结合三个查询的Symfony2原则

结合三个查询的Symfony2原则,symfony,Symfony,我正在构建一个简单的任务规划器。这是文件TaskController.php中的一个片段。我如何将这3个查询(任务、未完成、已完成)结合起来使其工作?我应该使用DQL吗 /** * Lists all task entities. * * @Route("/", name="task_index") * @Method("GET") */ public function indexAction() { $em = $this->getDoctrine()->ge

我正在构建一个简单的任务规划器。这是文件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,
    ));


}

最简单的解决方案是在控制器中过滤任务:

$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,
    ));

在此解决方案中,您只执行一个DB查询,而不是三个查询。

您可以使用条令的
\doctor\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,
));

我想显示已登录用户的所有已完成任务,然后显示未完成的已登录用户任务。酷,它可以工作!只是想知道,有没有一种方法可以使用DQL来实现这一点?@Blazej我不这么认为;这是可能的,但请看这里:您可以在DTO的构造函数中实现此逻辑。或者更好的办法是创建一个存储库方法来处理这个逻辑。此外,如果您正在使用我的答案,请接受我的答案(一般想法/规则)