是否可以从Laravel的关系表的关系表中获取数据?

问题描述:

说我有3个表是否可以从Laravel的关系表的关系表中获取数据?

Users 
- id 
- name 

Phones 
- id 
- number 
- user_id 

Carriers 
- id 
- name 
- phone_id 

Models,我将所有必要hasManybelongsTo关系。与carrier

App\User::with('phones')->where('id', '=', 1)->first();

phone

我可以使用选择userphones

App\Phone::with('carrier')->where('id', '=', 1)->first();

是否有可能得到同时具有phonecarrier使用模型集合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; 
+0

辉煌,谢谢。 – Harrison