2015-06-12 59 views
0

我理解查詢生成器如何工作,但我試圖正確使用ORM。Symfony2 - 通過父項屬性對象查找

我有兩個實體:天與任務

任務實體與日實體與多對一關聯。

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; 
    } 
} 

這裏是我的控制器:

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

正如您所看到的,我的請求性能不佳。我想找到按天數編號的任務。我能怎麼做?

謝謝

回答

0

存儲庫是您的解決方案。

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; 
    } 
} 

找到你1天的任務使用:

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

謝謝,我終於放棄使用查詢生成器。 – mctroubleshooter