jeudi 23 août 2018

Laravel 5.6 - Efficiently get relation count and last value of updated_at column

Lets say I have Posts and Comments defined as:

Post.php

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

Comment.php

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

I'd like to efficiently load Post with number of comments and the updated_at column of the comment which was updated last. How would I proceed?

The best I could think of is to load Post with all Comments but constrain the select on Comments to post_id, and updated_at columns. Then in the view count the loaded Comments to get the count and use sortByDesc('updated_at')->first() to get the date of last column:

MyController.php

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

my_view.blade.php

Comments count: 
Last comment: 

Is there a way to do this more efficiently and only get the count of comments and value of latest comments.updated_at column?

MySQL or Eloquent solution is OK.

Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire