2016-12-02 69 views
1

我正在構建一個簡單的任務計劃程序。這是來自文件TaskController.php的一個片段。我如何將這3個查詢(任務,未完成,已完成)組合起來使其工作?我應該使用DQL嗎?Symfony2結合三個查詢的原則

/** 
* 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

我想顯示已登錄用戶的所有完成的任務和登錄用戶的那麼沒有完成任務。 – Blazej

回答

3

您可以使用學說的\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, 
)); 
+0

酷,它的工作原理!只是想知道,有沒有辦法使用DQL來做到這一點? – Blazej

+1

@Blazej我不認爲這是可能的,但可以直接看看這裏:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language .html#new-operator-syntax您可以在DTO的構造函數中實現此邏輯。或者更好的想法是創建一個存儲庫方法來處理這個邏輯。另外,如果你使用它,請接受我的答案(一般StackOverflow的想法/規則) – Xymanek

+1

@Xymanek,這是一個非常優雅的解決方案:) –

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

在這個解決方案,您正在做的只有一個DB查詢,而不是三個查詢。