关系laravel:计数数据

模型 Category

public function product()
{
    return $this->hasMany(products::class);
}

模型 product

public function category()
{
    return $this->belongsTo(Category::class);
}

我在控制器中处理:

$result = Category::select(['id','name'])
    ->with(['product:category_id,status'])
    ->where('order',1)
    ->get();

打印原始数据时的结果:

[
  'id' => 1,'name' => 'Hot'
  'product' => [
     'status' => 1,'category_id' => 1
   ]
]
[
   'id' => 2,'name' => 'New'
   'product' => [
      'status' => 2,'category_id' => 2
   ]
]
..........

我得到了类别 idname 的列表,并根据关系得到了产品数据数组。在我的产品表中,有一个 status 列,其值等于 1,2,3。

现在我想通过使用该关系获得的产品数组计算有多少个 status = 1 和多少个 status = [2,3]?

dianzishu630 回答:关系laravel:计数数据

您可以使用 withCount 计算相关数据。假设您需要总计产品、状态 1 产品和状态 23 产品。

$result = Category::select(['id','name'])
    ->with(['product:category_id,status'])
    ->withCount([
        'product','product as status_one_product' => function ($query) {
            $query->where('status',1);
         },'product as status_other_product' => function ($query) {
              $query->whereIn('status',[2,3]);
          }
     ])
     ->where('order',1)
     ->get();

现在你可以得到像

这样的计数数据
echo $result[0]->product_count; // total product
echo $result[0]->status_one_product; // total product with status 1
echo $result[0]->status_other_product; // total product with status 2 and 3
本文链接:https://www.f2er.com/1639.html

大家都在问