【发布时间】:2017-04-03 21:38:57
【问题描述】:
我正在尝试计算一个类别中的所有文件,并且我有这两种关系:
public function files() {
return $this->hasMany('App\File', 'category_id','category_id');
}
public function fileCount() {
return $this->files()->selectRaw("category_id, count(*) AS count")
->groupBy('category_id');
}
这给了我一个项目集合,其中count 属性可以像这样访问:
$my_category = Category::where("category_id", category_id)->with('fileCount')->get();
$file_counter = $my_category->first()->fileCount->first()->count;
是否可以直接将count 属性附加到$my_category 变量?任何建议将不胜感激。
【问题讨论】:
标签: laravel count eloquent has-many relationships