2015-12-03 79 views
2

我已經表所示:product_id->名稱,描述,價格Symfony的3學說如何建立一個沒有列索引後綴查詢

我想要檢索的所有產品,所以這是我的代碼檢索產品

$doc = $this->getDoctrine(); 
    $em = $doc->getEntityManager(); 
    $conn = $em->getConnection(); 
    $repo = $doc->getRepository('AppBundle:Products'); 
    $query = $repo->createQueryBuilder('p')->getQuery(); 
    $sql = $query->getSql(); 
    $stmt = $conn->prepare($sql); 
    $stmt->execute(); 
    $products = $stmt->fetchAll(\PDO::FETCH_ASSOC); 

問題是構建查詢其列名作爲別名後總是添加列索引後綴時

那麼結果會是這樣的:

[ 
    {"product_id_0":"1","name_1":"Name1","description_2":"Desc1","price_3":"100"}, 
    {"product_id_0":"2","name_1":"Name2","description_2":"Desc2","price_3":"200"} 
] 

注意到他們都喜歡_0,_1後綴後,我不想要它, 我怎樣才能建立查詢,而無需像別名列名?

+0

替換您最後用$查詢 - > fetchArray線。更好的是,使用fetchAll並使用對象。 http://doctrine-orm.readthedocs.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html – Cerad

+0

@Cerad它們在類Doctrine \ ORM \ Query中沒有名爲fetchArray的方法,學說\ DBAL \聲明。 –

+0

我輸入得太快了。 $查詢 - > getArrayResult()。 http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#query-result-formats – Cerad

回答

0

您已經有一個存儲庫。

當您有一個存儲庫時,您不需要創建原始SQL查詢或甚至使用創建的查詢。讓Doctrine處理這個問題(這是DBAL,Doctrine的數據庫抽象層)。

取而代之,請使用類似findAll()findBy()的方法來獲取對象。

例子:

$repo = $doc->getRepository('AppBundle:Products'); 
$results = $repo -> findAll(); 

// Returns array(Product, Product, ...), which should be mapped to an entity 
// so that you can use $product -> getName() or whatever you need. 

您還可以創建一個查詢來獲取一個數組結果:

$results = $repo -> createQueryBuilder('p') -> getQuery() -> getArrayResult(); 

文檔:http://symfony.com/doc/current/book/doctrine.html

+0

謝謝,我有另一個問題... 如果我想獲得真正的列,我定義product_id而不是productId我該怎麼做? –

+0

看我的編輯.... – Hidde