Laravel Eloquent 带计数器的模型

Laravel Eloquent model with counter

我正在尝试计算一个类别中的所有文件,并且我有以下两种关系:

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 变量?任何建议将不胜感激。

您可以使用withCount()方法:

$my_category = Category::where("category_id", category_id)
                       ->withCount(['files' => function($q) {
                           $q->groupBy('category_id');
                       })
                       ->get();

这会将 files_count 属性放入结果中。

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models