1

I'm building a simple task planner. This is a fragment from the file TaskController.php. How can I combine these 3 queries (tasks, notcompleted, completed) to make it work? Should I use 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,
    ));


}
1
  • I want to show all completed tasks of the logged user and then not completed tasks of the logged user. Commented Dec 2, 2016 at 17:15

2 Answers 2

3

You can use Doctrine's \Doctrine\Common\Collections\Collection::partition() to split the tasks:

$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,
));
Sign up to request clarification or add additional context in comments.

2 Comments

Cool, it works! Just wondering, is there a way to do this using DQL?
@Blazej I don't think it;s possible directly but take a look here: docs.doctrine-project.org/projects/doctrine-orm/en/latest/… You can implement this logic in the DTO's constructor. Or a better idea would be to make a repository method to handle this logic. Also, please accept my answer if you are using it (general StackOverflow idea/rule)
0

The simplest solution could be to filter tasks in the controller:

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

In this solution you are doing only one DB query, instead of three queries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.