2017-03-03 132 views
0

我有以下選擇一個查詢生成器:Symfony的學說的QueryBuilder添加where子句上加入

$starterRepository = $this->getDoctrine() 
          ->getManager() 
          ->getRepository('CatalogBundle:Starter'); 

$query = $starterRepository->createQueryBuilder('s') 
          ->where('s.active = 1') 
          ->orderBy('s.voltage, s.power, s.serial'); 

它選擇表「首發」,但裏面Starter.php我有一個協會「引用」像這樣:

/** 
* @var ArrayCollection 
* 
* @ORM\ManyToMany(targetEntity="StarterReference", inversedBy="starters") 
* @ORM\JoinTable(name="starters_references") 
*/ 
protected $references; 

因此,在我的查詢結果中,我有「starters」和「starters_references」表。 1啓動器有許多啓動器參考。現在問題是我需要選擇的不是所有的啓動器引用,而只是那些在名爲「ref_usage」的列中有一些值的啓動器引用。

所以我需要寫在where子句中我的查詢,我想這樣的:

->where('reference.ref_usage = 1') 

不過這樣一來,我得到只有一個「啓動」項與所有已列入參考文獻。我需要所有初級項目,但只有參考ref_usage 1.

任何想法?

這是我使用的完整文件和功能。

控制器功能: http://pastebin.com/0tTEcQbn

實體 「Starter.php」: http://pastebin.com/BFLpKtec

實體 「StarterReference.php」: http://pastebin.com/Kr9pEMEW


編輯: 這是我的查詢如果我使用:

->where('reference.ref_usage = 1') 

SELECT COUNT(*) AS dctrn_count FROM (SELECT DISTINCT id0 FROM (SELECT s0_.id AS id0, s0_.serial AS serial1, s0_.voltage AS voltage2, s0_.power AS power3, s0_.rotation AS rotation4, s0_.teeth AS teeth5, s0_.module AS module6, s0_.b_terminal AS b_terminal7, s0_.comment AS comment8, s0_.commenten AS commenten9, s0_.commentru AS commentru10, s0_.commentpl AS commentpl11, s0_.commentde AS commentde12, s0_.commentes AS commentes13, s0_.type AS type14, s0_.adaptation AS adaptation15, s0_.alternative_product_1 AS alternative_product_116, s0_.alternative_product_2 AS alternative_product_217, s0_.alternative_product_3 AS alternative_product_318, s0_.alternative_product_4 AS alternative_product_419, s0_.active AS active20 FROM starters s0_ INNER JOIN starters_references s2_ ON s0_.id = s2_.starter_id INNER JOIN starter_reference s1_ ON s1_.id = s2_.starterreference_id WHERE s0_.active = 1 AND s1_.ref_usage = 1 ORDER BY s0_.voltage ASC, s0_.power ASC, s0_.serial ASC) dctrn_result) dctrn_table

正如你可以看到它增加了ref_usage = 1 where子句。但問題是我不需要它,我只需要在內部加入我的引用時檢查ref_usage。

+0

完整查詢構建器請 – Hooli

+0

添加了我正在使用的整個文件。發佈編輯。 – The50

回答

2

您應該在查詢中加入引用,然後添加where子句。

$query = $starterRepository->createQueryBuilder('s') 
         ->join('s.references', 'reference') 
         ->where('s.active = 1') 
         ->andwhere('reference.ref_usage = 1') 
         ->orderBy('s.voltage, s.power, s.serial'); 
+0

我用過 - >和where('reference.usage = 1'),但是這樣我得到的只有一個字段。我需要獲得所有初學者,加入啓動器引用(不是所有的引用,只有ref_usage = 1的引用)。 – The50