I am trying to limit on hasMany relation in laravel but instead of each post it limit on whole or all records. Below is my code for explanation.
class Post extends Model {
protected $table = "user_posts";
protected $appends = ['logged_in_user_id', 'comments_count'];
public function user() {
return $this->belongsTo('App\User');
}
public function comments() {
return $this->hasMany('App\Comment')->take(2);
}
}
I am trying to get 2 or 3 recent comment on each post as below
$posts = \App\Post::orderBy('updated_at', 'DESC')->with('comments')->where('user_posts.user_id', $user_id)->paginate(10);
Problem is instead of giving 2 comment for each post, it gives only 2 comment from all the fetched post.
Current result: Post1:
- Comment 1
- comment 2 Post2: No comment loaded in post 2 because it limits on whole.
Expected: post1:
- comment 1
- comment 2
post2:
- comment 1
- comment 2
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire