Eager 加载 Laravel Eloquent 相关模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17103272/
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
Eager load Laravel Eloquent related model
提问by ArthurGuy
I am trying to get eager loading working when fetching related models.
在获取相关模型时,我试图让急切加载工作。
public function allCompanies() {
$companies = $this->companies()->active()->get();
$companies->load('Industry');
return $companies;
}
I have this function on the model Industry and I believe this should fetch the companies which are within the current industry, it should also fetch the related industry for the companies (this will be the current record)
我在模型行业有这个功能,我相信这应该获取当前行业内的公司,它还应该为公司获取相关行业(这将是当前记录)
This doesn't seem to work as when I iterate over the companies it re-fetches the Industry for each one.
当我遍历公司时,这似乎不起作用,它为每个公司重新获取行业。
Am I doing something wrong with the $companies->load('Industry');
line?
我的$companies->load('Industry');
线路有问题吗?
Thanks
谢谢
回答by anthony.c
Try:
尝试:
public function allCompanies() {
$companies = $this->companies()->active()->with('industry')->get();
return $companies;
}
The with()and load()functions are referencing functions within the model not the model itself ie:
所述带()和负载()函数模型不是模型本身即内引用的功能:
class Company extends Eloquent {
public function industry()
{
return $this->belongsTo('Industry');
}
}
class Industry extends Eloquent {
public function companies()
{
return $this->hasMany('Company');
}
}
Please reference http://laravel.com/docs/eloquent#eager-loading