Get count of relations from eloquent collection

2750 views mysql
9

I have Call model. Each call has Theme. How i did this:

class Call extends Model
{
    // some code here

    public function theme()
    {
        return $this->hasOne(Theme::class, 'id', 'theme_id')->withTrashed();
    }

    // some code there
}

This works great. What i want to do is get count of each themes used in all calls.

There is 200 calls for example. 100 of them has theme_id=3, 50 of them has 6, and last 50 has 8. I want to get result like:

{
  {theme_id:3, themes_count=100},
  {theme_id:6, themes_count=50},
  {theme_id:8, themes_count=50},
}

How to do that?

answered question

1 Answer

13

\DB::select("select theme_id, count(*) themes_count from calls group by theme_id");

posted this

Have an answer?

JD

Please login first before posting an answer.