我有一个查询构建器,其中包含以下选择:
$starterRepository = $this->getDoctrine()
->getManager()
->getRepository('CatalogBundle:Starter');
$query = $starterRepository->createQueryBuilder('s')
->where('s.active = 1')
->orderBy('s.voltage, s.power, s.serial');
它选择表" starters",但在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 :(得分:4)
您应该在查询中加入引用,然后添加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');