Laravel Eloquent With() With()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37576620/
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 With() With()
提问by Scott Robinson
How do I go about using multiple Eloquent With()'s?
我该如何使用多个 Eloquent With()?
PortalPlaylistElement Model
PortalPlaylistElement 模型
class PortalPlaylistElement extends Model
{
public $primaryKey = 'code';
public $incrementing = false;
public $timestamps = false;
public function AirtimePlaylists()
{
return $this->hasOne('App\AirtimePlaylist','id','playlist_id');
}
}
AirtimePlaylistContent Model
通话时间播放列表内容模型
class AirtimePlaylistContent extends Model
{
protected $table = 'cc_playlistcontents';
}
AirtimePlaylistModel
通话时间播放列表模型
class AirtimePlaylist extends Model
{
protected $table = 'cc_playlist';
public function PortalPlaylistElements()
{
return $this->belongsTo('App\PortalPlaylistElement','playlist_id');
}
public function AirtimePlaylistContents()
{
return $this->hasMany('App\AirtimePlaylistContent','playlist_id');
}
}
I have no problems with:
我没有任何问题:
AirtimePlaylist::with('AirtimePlaylistContents')->get());
or
或者
PortalPlaylistElement::with('AirtimePlaylists')->get();
But I'd like to get all AirtimePlaylistContents, in an AirtimePlaylist that belongs to a PortalPlaylistElement.
但我想在属于 PortalPlaylistElement 的 AirtimePlaylist 中获取所有 AirtimePlaylistContents。
In essence, (Pseudo code)
本质上,(伪代码)
PortalPlaylistElement::with('AirtimePlaylists')::with('AirtimePlaylistContents')->get();
回答by huuuk
You need Nested Eager Looading
你需要嵌套的急切加载
PortalPlaylistElement::with('AirtimePlaylists.AirtimePlaylistContents')->get();
回答by Achraf Khouadja
nested relations
嵌套关系
with('relation1.relation2.relation3')->get(); // relation1 has relation2 relation2 has relation 3
not nested relations
非嵌套关系
with('relation1','relation2','relation3')->get(); // you model has all relations
回答by Daniel Raouf
I would like to add this if someone needed it
如果有人需要,我想添加它
with(['relation1.relation2-1','relation1.relation2-2'])->get(); // relation1 has relation2-1 and relation1 also has relation2-2