laravel和sql分组问题

时间:2019-05-16 15:56:59

标签: php sql laravel eloquent

首先,我在计算每天销售的产品时遇到问题。在sql中,我有查询

skkk.casts()

这对我来说很有趣,但我使用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-我也需要显示名称,但我不知道该怎么做

第二,我想在Laravel中使用它,所以也许有人知道在Eloquent中有可能做到这一点吗?

预先感谢您:)

2 个答案:

答案 0 :(得分:2)

我将withCount()select(DB::raw())结合使用,像这样:

$products = Product::withCount(['invoices as quantity' => function ($query) {
    $query->select(DB::raw('sum(quantity)'));
}])->get();

然后,您可以像这样访问每个数量总和:

$quantity = $products->first()->quantity;

答案 1 :(得分:1)

您需要更新模型关系才能实现。

型号:

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');