Laravel Eloquent:如何从多个表中进行选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43088258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent: How to select from multiple tables
提问by Pattle
I'm using Laravel and the Eloquent ORM that it provides but I'm struggling to select the data I need. I have 3 Models
我正在使用 Laravel 和它提供的 Eloquent ORM,但我正在努力选择我需要的数据。我有 3 个模型
- House
- Occupants
- Job
- 房子
- 住户
- 工作
A house can have multiple occupants and I can easily get these using the following.
一所房子可以有多个居住者,我可以使用以下方法轻松获得这些。
$house= House::find($house_id);
$occupants = $house->occupants()->where('active', 1)->get();
This works nicely but I also want to select the job of each occupant. I've got this as a one to one relationship but the jobs are in a seperate table.
这很好用,但我也想选择每个住户的工作。我把它作为一对一的关系,但工作在一张单独的桌子上。
Is there a way to also select the related jobfor each occupant from the jobs table efficiently? I'm guessing it would be something like this
有没有办法有效地从工作表中为每个占用者选择相关工作?我猜它会是这样的
$occupants_and_jobs = $house->occupants()->where('active', 1)->job()->get();
回答by apokryfos
You could just try what you are suggesting and see what happens. You can also do some eager loadingof the relationships
你可以试试你的建议,看看会发生什么。您还可以对关系进行一些急切加载
$house = House::with(["occupants","occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
print_r($occupant->job);
}
As @AlexeyMezenin if you need to constrain the relationship then you need to (as the docssuggest under Constraining Eager Loads) do:
作为@AlexeyMezenin,如果您需要限制关系,那么您需要(正如文档在Constraining Eager Loads下建议的那样)执行以下操作:
$house = House::with(["occupants" => function ($query) {
$query->where("active","=",1);
},"occupants.job"])->find($house_id);
foreach ($house->occupants as $occupant) {
print_r($occupant->job);
}
Now the fine-print: Laravel will include "with" relationships in the order it finds them and also include all intermediate relationships of the nesting, e.g. ::with("occupants.job")
implies ::with(["occupants","occupants.job"])
however if you already have set a previous relationship then it is maintained (which is how this works). occupants
will not be overwritten when occupants.job
is set.
现在的精细打印:Laravel将包括“与”中找到他们,同时也包括嵌套的所有中间关系的顺序,如关系::with("occupants.job")
意味着::with(["occupants","occupants.job"])
但如果你已经设置了以前的关系则维持(这是这是如何工作的)。设置occupants
时不会被覆盖occupants.job
。
回答by Alexey Mezenin
This query will load all occupants with active = 1
and their jobs:
此查询将加载所有居住者active = 1
及其工作:
House::with(['occupants' => function($q) {
$q->where('active', 1);
}, 'occupants.job'])->find($house_id);