Laravel已售物品数量

时间:2017-12-07 14:45:31

标签: php laravel laravel-5

我想要计算每个卖家的已售商品。 我尝试更改此代码:

<?php $count = DB::table('purchases')->whereIn('seller_id', [4])->count(); echo $count; ?>

我可以在其中添加其他$ DB命令吗?

{{$product->seller->id}}

例如,而不是[4]

<?php $count = DB::table('purchases')->whereIn('seller_id', [{{$product->seller->id}}])->count(); echo $count; ?>

2 个答案:

答案 0 :(得分:3)

试试这个:

在卖家模型中

public function purchases(){
    return $this->hasMany(Purchase::class)
}

然后

$seller = Seller::withCount('purchases')->find(4);

echo $seller->purchases_count;

$purchases = Seller::find(4)->purchases;

echo $purchases->count();

答案 1 :(得分:0)

如果您想获得一组用户的计数,可以使用whereIn和一系列卖家ID。

但是如果你想为每个卖家计算一次,你应该使用分组

->groupBy('seller_id')

以便您的查询看起来像:

$user_info = DB::table('purchases')
             ->select('seller_id', DB::raw('count(*) as total'))
             ->groupBy('seller_id')
             ->get();
相关问题