Symfony2 - Find by a parent property object

1.1k Views Asked by At

I understood how Query Builder works but I am trying to use the ORM correctly.

I have two entities: Days and Tasks

The Tasks entity is linked to the Day Entity with a ManyToOne association.

Tasks.orm.yml

DJU\ MyBundle\ Entity\ Tasks:
  type: entity
table: null
repositoryClass: DJU\ MyBundle\ Entity\ TasksRepository
id:
  id:
  type: integer
id: true
generator:
  strategy: AUTO
fields:
  description:
  type: text
manyToOne:
  days:
  targetEntity: Days
inversedBy: tasks
joinColumn:
  name: days_id
referencedColumnName: id

Tasks.php

class Tasks {
    /**
     * Get temps
     *
     * @return \CIT\CalendarBundle\Entity\Temps 
     */
    public function getTemps()
    {
        return $this->temps;
    }
}

Here is my controller:

class DefaultController extends Controller
{
     public function example2CalAction() {
        $em = $this->getDoctrine()->getManager();
        $tasks = $em->getRepository('DJUMyBundle:Tasks')->findAll();
        
        foreach($tasks as $onetask) {
            if ( $onetask->getDays()->getId() == '1' ) {
                $myt = $onetask->getDays();
            }
        }    
        return $this->render('DJUMyBundle:Default:sample2.html.twig', array('tasks' => $myt));
    }
}

As you can see my request has poor performance. I would like to find Tasks by Days id. How can I do?

Thank you

1

There are 1 best solutions below

1
On

Repositories are your solution.

class TasksRepository {
    public function findByDay(Day $day)
    {
        $q = $this
        ->createQueryBuilder('t')
        ->select('t')
        ->leftJoin('t.days', 'd')
        ->where("d.id = :dayId")
        ->setParameter('dayId', $dayId)
        ->getQuery();
        $result = $q->getResult();

        return $result;
    }
}

Find your tasks for day 1 using:

$day = $em->getRepository('DJUMyBundle:Day')->find(1);
$tasks = $em->getRepository('DJUMyBundle:Tasks')->findByDay($day);