2015-07-10 85 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 
     )); 
} 

我的答案返回一个数组,但你可以在仓库内使用查询生成器,并返回一个对象......这两种方法工作,我只是喜欢我的方法。