雄辩的嵌套关系与一些约束 [英] Eloquent Nested Relation with Some Constraint
问题描述
我有以下三个表:
A
-------------
| id | name |
-------------
B
--------------------
| id | A_id | name |
--------------------
C
--------------------
| id | B_id | name |
--------------------
因此,表 C
中的数据属于表 B
中的数据,属于表中的数据 A
。现在,我想查询 C
,同时还从 B
和 A
和以下代码做的伎俩很好。
So, the data in table C
belongs to the data in table B
which belongs to the data in table A
. Now, I want to query C
, while also retrieving data from B
and A
and the following code does the trick just fine.
C::with('B.A')->get();
现在的问题是,我想查询 C
有一些约束。其中一个约束是 id
A
。我尝试了以下内容:
The problem now, is that I want to query C
with some constraints. One of these constraints is the id
of A
. I've tried the following:
C::with(array('B.A' => function ($query)
{
$query->where('id', '=', $constraint);
}))->get();
但是似乎Eloquent会检索 C
甚至不考虑约束,除非它执行查询以检索表 A
中的数据。如何解决这个问题?我需要在 C
中添加另一个字段,即 A_id
,并匹配 $ constraint
对于该字段
But it seems that Eloquent will retrieve all the rows in C
without even taking the constraint into account, except when it's executing the query to retrieve data in table A
. How do I get around this problem? Do I need to add another field in C
, that is A_id
, and match $constraint
against that field?
推荐答案
您将与() / code>方法与SQL的
JOIN
,发生了很多。
当您使用 Foo :: with('bar') - > where_something(1)
时,Laravel将首先加载 Foo
然后,根据 Foo.bar_id
,它将加载 Bar
。它的目的是告诉Laravel对您的模型的加载依赖关系的组合查询,大大提高了这些模型的迭代性能。
When you use Foo::with('bar')->where_something(1)
, Laravel will first load the Foo
and then, based on Foo.bar_id
, it will load the Bar
. It serves the purpose of telling Laravel to eager load dependencies of your model on a combined query, greatly improving performance of iterations on those models.
如果不使用它应执行以下查询:
If you don't use it, the following queries should be executed:
SELECT * FROM foos WHERE foos.something = 1;
SELECT * FROM bars WHERE bars.id = 30;
SELECT * FROM bars WHERE bars.id = 57;
SELECT * FROM bars WHERE bars.id = 134;
SELECT * FROM bars WHERE bars.id = 1096;
另一方面,如果您使用它:
If you use it, on the other hand:
SELECT * FROM foos WHERE foos.something = 1;
SELECT * FROM bars WHERE bars.id IN (30, 57, 134, 1096); // Eager loading
当您使用(),你只是限制这些依赖关系的热切加载,而不是第一个查询。
When you add a condition to that with()
, you are only constraining the eager loading of those dependencies, and not the first query.
为了达到你想要的目的,你需要使用 - > join()
。
To achieve what you want, you'll need to use ->join()
.
C::with(array('b', 'b.a'))
->join('b', 'b.id', '=', 'c.b_id')
->join('a', 'a.id', '=', 'b.a_id')
->where('a.id', '=', $ID)
->get('c.*');
我已经将与()
,因为我不知道你是否需要访问 $ c-> b-> a
。如果不这样做,而您只需要 $ c
数据,则可以使用()删除,因为它将不必要地查询B和A。
I've included the with()
, because I didn't know if you would need to access $c->b->a
. If you don't, and you just need $c
data, you can remove the with()
since it will query for B's and A's unnecessarily.
这篇关于雄辩的嵌套关系与一些约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!