Laravel withCount use function in model

Mafys Grif

I have model Post:

 protected $guarded = [];

 public function reviews() {
      return $this->hasMany(Review::class);
 }

My reviews table have a column type with values: 1(good),2(comment),3(negative). I need get count reviews for every type. I need globally get these counts. I know that I can do in model something like this:

 protected $withCount = ['reviews'];

But this get me all reviews. But I need get count only for every type.

Piazzi

You could use the withCount method and do sub queries inside:

$counts = Post::withCount([
'reviews',
'reviews as good_reviews' => function ($query) {
    $query->where('type', 1);
}],
'reviews as bad_reviews' => function ($query) {
    $query->where('type', 3);
}],

}])->get();

You can access the count like this:

echo $counts[0]->good_reviews;

For more info: Docs

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related