Answer the question
In order to leave comments, you need to log in
How to solve N+1 DB query issue when fetching model with getNameAttribute?
There is a feedback system for posts that works like this: You can leave a review for a post, and a comment for a review. It turns out 3 models Post, Review, Comment. In the Post model, I create a new attribute that returns the number of comments on a post via the comments of that post.
public function getCommentsCountAttribute() : int
{
return $this->hasManyThrough(
Review::class,
Comment::class,
'commentable_id',
'reviewable_id'
)
->where('commentable_type', Review::class)
->count();
}
Post::with()
or is it necessary to load all reviews in advance in posts, with preloaded comments, and then work with already loaded data in the method? Or is there a better way?
Answer the question
In order to leave comments, you need to log in
This is what should work:
public function reviews(): HasManyThrough
{
return $this->hasManyThrough(
Review::class,
Comment::class,
'commentable_id',
'reviewable_id'
);
}
public function getCommentsCountAttribute(): int
{
return $this
->reviews
->where('commentable_type', Review::class)
->count();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question