2016-12-02 10 views
1

私は単純なタスクプランナーを構築しています。これは、TaskController.phpファイルからのフラグメントです。どのように私はこれら3つのクエリ(完了していない、完了した)を組み合わせて動作させることができますか?私はDQLを使うべきですか?symfony2 3つのクエリを組み合わせた教義

/** 
* 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の\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, 
    )); 

は、次の3つのクエリの代わりに、唯一のDBクエリを行っています。

関連する問題