【问题标题】:Laravel Eloquent model with counterLaravel Eloquent 模型与计数器
【发布时间】: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


    【解决方案1】:

    你可以使用withCount()方法:

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

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

    如果您想在不实际加载关系的情况下计算关系结果的数量,您可以使用 withCount 方法,该方法会在结果模型上放置一个 {relation}_count 列

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 2021-07-04
      • 2013-02-26
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 2016-12-14
      相关资源
      最近更新 更多