是否可以从Laravel的关系表的关系表中获取数据?
问题描述:
说我有3个表是否可以从Laravel的关系表的关系表中获取数据?
Users
- id
- name
Phones
- id
- number
- user_id
Carriers
- id
- name
- phone_id
在Models
,我将所有必要hasMany
和belongsTo
关系。与carrier
App\User::with('phones')->where('id', '=', 1)->first();
和phone
:
我可以使用选择user
与phones
App\Phone::with('carrier')->where('id', '=', 1)->first();
是否有可能得到同时具有phone
和carrier
使用模型集合App\User
?
答
您可以使用Nested eager loading:
$users = App\User::with('phones.carriers')->get();
或者,
设置Has Many Through关系在用户模型:
public function carriers()
{
return $this->hasManyThrough('App\Phone', 'App\Carrier');
}
,这样你可以得到运营商和手机:
$user->carriers;
$user->phones;
辉煌,谢谢。 – Harrison