[英]Eloquent Count nested relationships
| Data | DataChildren | Category
----------------------------------
| id | id | id
| name | data_id | name
| | category_id |
| | name |
Data Model:数据 Model:
public function data_children() {
return $this->hasMany(DataChildren::class, 'data_id', 'id');
}
DataChildren Model:数据子 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
.我想通过
DataChildren
根据Data
id 获取Category
的数量。 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
我试过使用这个但返回
null
Data::withCount(['category'=> function($query){return $query->groupBy('category_id');}])->find(1);
you need to used many to many relationship你需要使用多对多关系
in Category Model:在类别 Model 中:
public function datas()
{
return $this->belongsToMany(Data::class, 'data_childerens', 'category_id', 'data_id');
}
Then run this Query withCount :然后运行此查询withCount :
Category::withCount('datas')->get();
Set Data Model:设置数据 Model:
public function categories()
{
return $this->belongsToMany(Category::class, 'data_childerens', 'data_id', 'data_id');
}
Then run this Query With and withCount :然后运行此查询 With 和withCount :
Data::with('categories')->withCount('datas')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.