Eloquent Count nested relationships

萝らか妹 提交于 2021-02-11 12:20:30

问题


| 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);

回答1:


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();


来源:https://stackoverflow.com/questions/65953937/eloquent-count-nested-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!