简体   繁体   English

一对多关系的学说查询

[英]doctrine query for chained one-to-many relationships

I have three tables A, B, C. A and B have a one-to-many relationship. 我有三个表A,B,C。A和B具有一对多关系。 B and C have another one -to-many relationship. B和C具有另一对多关系。 In another word, each A can have multiple Bs, while each B can have multiple Cs. 换句话说,每个A可以具有多个B,而每个B可以具有多个C。

Now I want to do a query for a given record of A, to get all the related Bs which have related Cs. 现在,我想查询给定记录A,以获取所有具有相关C的相关B。 In another word, for a given a, which is a record in table A, I want to get all of the related Bs from table B, providing that each of the Bs also has more than zero related Cs in table C. 换句话说,对于给定的a(表A中的一条记录),我想从表B中获取所有相关的B,条件是每个B在表C中的相关C也都大于零。

How to write the statement in PHP doctrine? 如何用PHP原则编写语句? I have some code which doesn't work: 我有一些无效的代码:

Doctrine_Query::create()->from('B b')->leftJoin('C c') ->andWhere('b.A_id = ?', a.id)->andWhere('c.b_id = b.id'); Doctrine_Query :: create()-> from('B b')-> leftJoin('C c')-> andWhere('b.A_id =?',a.id)-> andWhere('c.b_id = b 。ID');

From my workings with Doctrine, this is not possible (Doctrine 1 is what I am speaking to). 从我与Doctrine的合作中,这是不可能的(我要说的是Doctrine 1)。

The work around, which I know sucks, is to do multiple queries. 我知道很糟糕的解决方法是执行多个查询。 IE take all of the B id's and use them in the whereIN clause and pull them up in a separate query. IE会获取所有B ID,并在whereIN子句中使用它们,并在单独的查询中将它们拉起。 If someone else has a better method I would be interested in it :) 如果其他人有更好的方法,我会对它感兴趣:)

As premiso noted you need to write at least 2 queries. 如前所述,您至少需要编写2个查询。 I would also do it the way he suggested (take all of B id's and use an IN). 我也将按照他的建议进行操作(获取所有B ID并使用IN)。

To make it more Doctrine-line, look at DQL Subqueries . 要使其更符合教义,请查看DQL子查询 They already show an example that uses IN in connection with selecting ID`s. 他们已经显示了一个使用IN与选择ID结合使用的示例。

edit : Reading DuoSRX's answer, I think you may have meant what he shows with Inner Joins but not quite sure if I understood the question correct. 编辑 :阅读DuoSRX的答案,我想您可能是说他用内联接显示的内容,但是不确定我是否理解正确的问题。

Why don't you just use an innerJoin ? 您为什么不只使用innerJoin?

With Foo, Bar and Baz (respectively A, B and C) : 使用Foo,Bar和Baz(分别是A,B和C):

Doctrine_Query::create()
->from('Bar bar')
->where('bar.foo_id = ?', $foo->id)
->innerJoin('bar.Baz baz');

This way you'll only get Bar which belongs to Foo, and which have one or many Baz. 这样,您将只获得属于Foo且具有一个或多个Baz的Bar。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM