首先,我对每天销售的产品进行统计时遇到了问题。在sql中,我有查询
select product_name, sum(quantity) as quantity from invoice_product
join invoices on invoices.id = invoice_product.invoice_id
join products on products.id = invoice_product.product_id
where invoices.issued_at = '2019-05-16'
and products.`made_by_us` = 1
group by product_name它向我展示了我感兴趣信息,但是我使用product_name来制作group by,但是我应该使用product_id -我也需要显示名称,但是我不知道怎么做。
其次,我想在Laravel中使用它,所以也许有人知道用Eloquent可以做到这一点?
提前感谢您:)
发布于 2019-05-17 04:31:51
我会将withCount()与select(DB::raw())结合使用,如下所示:
$products = Product::withCount(['invoices as quantity' => function ($query) {
$query->select(DB::raw('sum(quantity)'));
}])->get();然后,您可以像这样访问每个数量总和:
$quantity = $products->first()->quantity;发布于 2019-05-17 02:00:23
你需要更新你的模型关系来实现这一点。
型号:
InvoiceProduct模型
class InvoiceProduct extends Model
{
protected $table = 'invoice_product';
protected $guarded = [
'id',
];
}
public function invoice()
{
return $this->belongsTo('App\Invoice'); // Assuming `Invoice` Model is directly in app folder
}
public function product()
{
return $this->belongsTo('App\Product'); // Assuming `Product` Model is directly in app folder
}控制器:
$full_query = InvoiceProduct::whereHas('invoice', function ($query) {
return $query->where('issued_at', '2019-05-16');
})->whereHas('product', function ($query) {
return $query->where('made_by_us', 1);
});
$product_names = $full_query->get(['product_name']);
$total_quantities = $full_query->sum('quantity');https://stackoverflow.com/questions/56172447
复制相似问题