Skip to content
Advertisement

Eloquent Count nested relationships

| Data     | DataChildren   | Category
----------------------------------
|  id      | id             | id
|  name    | data_id        | name
|          | category_id    |
|          | name           |

Data Model:

public function data_children() {
   return $this->hasMany(DataChildren::class, 'data_id', 'id');
}

DataChildren Model:

public function category() {
     return $this->belongsTo(Category::class, 'category_id', 'id');
}

I want to get count of Category based on Data id through DataChildren. I just want to take the Category records from Data so the result should be like this

name from category | Count of category for Data
-------------------------------------------------
Unpublished        |   1
Published          |   3

I’ve tried using this but return null

Data::withCount(['category'=> function($query){return $query->groupBy('category_id');}])->find(1);

Advertisement

Answer

you need to used many to many relationship

in Category Model:

 public function datas()
 {
        return $this->belongsToMany(Data::class, 'data_childerens', 'category_id', 'data_id');
 }

Then run this Query withCount :

Category::withCount('datas')->get();

Set Data Model:

public function categories()
{
     return $this->belongsToMany(Category::class, 'data_childerens', 'data_id', 'data_id');
}

Then run this Query With and withCount :

Data::with('categories')->withCount('datas')->get();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement