【问题标题】:Get relation of relation attributes获取关系属性的关系
【发布时间】:2018-01-11 14:31:58
【问题描述】:

我想显示链接的 cmets 并显示 cmets 的 de 关系,即 user 和 userprofile...

dd($page->getRelation('links'));

Collection {#318 ▼
  #items: array:2 [▼
    0 => Link {#317 ▼
      #relations: array:2 [▼
        "comments" => Collection {#327 ▼
              #attributes: array:5 [▼
                "id" => 3
                "content" => "teste"
                "link_id" => 1
                "user_id" => 1
                "created_at" => "2018-01-11 00:47:32"
              ]
              #relations: array:2 [▼
                "user" => User {#330 ▶}
                "userProfile" => UserProfile {#326 ▶}
              ]
            }
          ]
        }

在我提出的观点中:

        @foreach($page->getRelation('links') as $link)
        <div class="link">

    <!--show de comments of link (ONLY FOR EXPLANATION)-->
@foreach()
        <div class="comments">
        SHOW DE ATTRIBUTE OF COMMENT AND ATTRIBUTE OF RELATIONS OF COMMENT (user, userprofile)
        </div>
@endforeach

        </div>

        @endforeach

【问题讨论】:

    标签: laravel


    【解决方案1】:

    请查看Eager Loading下的文档

    Eloquent 可以在查询父模型时“预先加载”关系。急切加载缓解了 N + 1 查询问题。 (...) 查询时,您可以使用 with 方法指定应该预先加载哪些关系。

    例如:

    $pages = App\Page::with("link")->get();
    
    foreach ($pages as $page) {
        echo $page->links->comments;
    }
    

    您也可以预先加载多个关系

    $pages = App\Page::with(['link', 'author'])->get();
    

    最后,你可以嵌套预加载关系

    o 急切加载嵌套关系,您可以使用“点”语法。为了 例如,让我们急切地加载这本书的所有作者和所有 一篇 Eloquent 陈述中的作者个人联系方式

    $pages = App\Page::with('link.comments')->get();
    

    【讨论】:

    【解决方案2】:

    首先在控制器函数中加载关系:

    $page = Page::where($allYourConditions)->with(['links' => 
    function($query){
      $query->with(['comments' => function($query){
        $query->with(['user', 'userProfile']);
      }]);
    }])->get();
    

    然后在视图文件中:

    @foreach($page->links as $link)
      <div class="link">
      @foreach($link->comments as $comment)
        <div class="comment">
          <div class="comment-user">{{$comment->user}}</div>
          <div class="comment-user-profile">{{$comment->userProfile}}</div>
        </div>
      @endforeach
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2014-03-25
      • 1970-01-01
      相关资源
      最近更新 更多