【问题标题】:Laravel Eloquent multiple method chainingLaravel Eloquent 多方法链接
【发布时间】:2015-11-18 04:02:29
【问题描述】:

我有一个带有 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();

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以使用with 方法预先加载关系。您还可以使用点符号来预先加载“嵌套”关系。

    例子:

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

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

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

    【讨论】:

      【解决方案2】:

      您必须pluck articles 收藏中的照片:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-06
        • 2023-03-07
        • 2016-02-11
        • 1970-01-01
        • 2016-07-22
        • 2018-01-09
        • 2015-01-15
        相关资源
        最近更新 更多