I have a Post, like and comment model
I want to get the Post data, comments data and count of likes in a post using relations in laravel.
Everything is working but from the below code i'm getting the likes array and I want the count without any looping. Is this possible with the Relation?
This is my PostController code with relation:
$posts = Post::with('user','comment')->get();
Post model:
public function comment(){
return $this->hasMany(Comment::class);
}
public function like(){
return $this->hasOne(Like::class);
}
Like Model:
public function post(){
return $this->belongsTo(Post::class);
}
Comment Model:
public function post(){
return $this->belongsTo(Post::class);
}
CodePudding user response:
Try this
$posts = Post::withCount('user')->withCount('comment')->get();
CodePudding user response:
Use the withCount()
helper with an array :
Post::withCount(['comment'])->get();
If you want you can customise your count :
Post::withCount([
'user',
'comment as comments_today_count' => function($query){
$query->where('created_at', '>', now()->subDays()
}])->get();
You should also use plural for your hasMany relationships :
public function comments(){
return $this->hasMany(Comment::class);
}
so that you can use it more explicitly :
foreach($post->comments as $comment){...}