代码之家  ›  专栏  ›  技术社区  ›  brnd0 Diego Ponciano

Laravel 5.6-有效获取更新的列的关系计数和最后一个值

  •  0
  • brnd0 Diego Ponciano  · 技术社区  · 8 年前

    假设我有 Posts Comments 定义为:

    public function comments()
    {
      return $this->hasMany('App\Comment');
    }
    

    注释.php

    public function post()
    {
      return $this->belongsTo('App\Post');
    }
    

    我想有效地加载Post number of comments 以及 updated_at 上次更新的注释的列。我该怎么做?

    我能想到的最好的办法是加载包含所有评论的Post,但是将select-on-Comments限制为 post_id 更新时间 sortByDesc('updated_at')->first() 要获取最后一列的日期:

    MyController.php

    Post::with([
      'comments' => function($q) {
        $q->select('post_id','updated_at');
      }
    ])->get();
    

    我的视图.blade.php

    Comments count: {{ $posts->comments->count() }}
    Last comment: {{ $posts->comments->sortByDesc('updated_at')->first()->updated_at }}
    

    comments.updated_at 专栏?

    MySQL或雄辩的解决方案是可以的。

    谢谢!

    1 回复  |  直到 8 年前
        1
  •  0
  •   Jonas Staudenmeir    8 年前

    你可以通过 withCount()

    Post::withCount([
        'comments',
        'comments as last_comment' => function($q) {
            $q->select(DB::raw('max(updated_at)'));
        }
    ])->get();
    
    Comments count: {{ $post->comments_count }}
    Last comment: {{ $post->last_comment }}