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

时间:2017-01-10 03:47:23

标签: mysql laravel eloquent

说我有3张桌子

Users
- id
- name

Phones
- id
- number
- user_id

Carriers
- id
- name
- phone_id

Models中,我设置了所有必要的hasManybelongsTo关系。

我可以使用user选择phones

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

phonecarrier

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

是否可以使用模型phone获取同时包含carrierApp\User的集合?

1 个答案:

答案 0 :(得分:1)

您可以使用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;
相关问题