Laravel Eloquent 多方法链接

Laravel Eloquent multiple method chaining

我有一个 laravel 的项目,我有一些如下表:

#users table:
->id
->username
->password

#profile table:
->id
->user_id
->firstname
->lastname

#articles table:
->id
->user_id
->title
->body

#photos table:
->id
->article_id
->path

获取用户文章照片我想知道我应该如何处理 eloquent 我在模型中设置了关系但是当我第一次尝试它时我注意到我不能只做类似

的事情
User::find(1)->articles()->photos();

然后我尝试了其他一些方法,但我失败了!
现在我想知道如何检索与用户及其文章相关的照片?
提前谢谢你们。

您可以使用 with 方法预先加载关系。您还可以使用点符号来预加载 "nested" 关系。

示例:

User::with('articles.photos')->find(1);

这将检索主键为 1 的用户。它还将检索用户的所有文章以及与这些文章相关的照片。

有关预加载和点表示法的文档:http://laravel.com/docs/5.1/eloquent-relationships#eager-loading

您必须 pluck 中的照片 articles collection:

$user = User::with('articles.photos')->find(1);

$photos = $user->articles->pluck('photos')->collapse();