2015-07-10 60 views
0

的模型是:獲得從車表數據

enter image description here

我的行動看起來像:

public function fahrzeugeAction() 
{ 
    $user = $this->get('security.token_storage')->getToken()->getUser(); 
    $userId = $user->getId(); 

    $repository = $this->getDoctrine() 
     ->getRepository('FPMAppBundle:Car'); 

    /* This is the normal Select and it is testet with the mysqlworkbench. 
     SELECT c.id, c.description, c.active 
     FROM car c 
     INNER JOIN customer cu ON cu.id = c.id_customer 
     INNER JOIN customer_user cuu ON cuu.id_customer = cu.id 
     WHERE c.active = 1 AND cuu.id_user = 1 
    */ 
    $em = $this->getDoctrine()->getEntityManager(); 
    $qb = $em->createQueryBuilder() 
     ->select('c.id, c.description, c.active') 
     ->from('Car', 'c') 
     ->innerJoin('Customer', 'cu', 'ON', 'c.idCustomer = cu.id') 
     ->innerJoin('CustomerUser', 'cuu', 'ON', 'cu.id = cuu.id_customer') 
     ->where('cuu.idUser = ?', $userId) 
     ->orderBy('c.id', 'ASC') 
     ->getQuery(); 

    $cars = $qb->getResult(); 
    return $this->render("FPMAllgemeinBundle:Fahrzeuge:overview.html.twig" 
     array(
      "cars" => $cars // I know that i have at the moment no variable named $cars 
     ) 
    ); 
} 

警告:get_class()預計參數1是對象,整定

當我使用正常的選擇語句,然後我得到了正確的結果。

+0

使用'createQueryBuilder()'你需要構建DQL而不是SQL也可以通過添加你的實體定義來更新你的問題 –

回答

1

我的建議是將您的查詢從控件移動到存儲庫中,似乎您已經擁有一個Car存儲庫並正在檢索它。

庫:

<?php 
namespace Acme\Entity\Repository; 

use Doctrine\ORM\EntityRepository; 

class CarRepository extends EntityRepository { 
    public function myMethodName() { 
     try { 
      $sql = "SELECT c.id, c.description, c.active 
         FROM car c 
       INNER JOIN customer cu ON cu.id = c.id_customer 
       INNER JOIN customer_user cuu ON cuu.id_customer = cu.id 
        WHERE c.active = 1 
         AND cuu.id_user = 1"; 

      $sth = $this->getEntityManager()->getConnection()->prepare($sql); 
      $sth->execute(); 

      return $sth->fetchAll(); 
     } catch (\PDOException $e) { 
      return false; 
     } 
    } 
} 

控制器:

public function fahrzeugeAction() { 
    $user = $this->get('security.token_storage')->getToken()->getUser(); 
    $userId = $user->getId(); 

    $cars = $this->getDoctrine() 
     ->getRepository('FPMAppBundle:Car') 
     ->myMethodName(); 

    return $this->render("FPMAllgemeinBundle:Fahrzeuge:overview.html.twig" 
     array(
      "cars" => $cars 
     )); 
} 

我的答案返回一個數組,但你可以在倉庫內使用查詢生成器,並返回一個對象......這兩種方法工作,我只是喜歡我的方法。