首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >group by laravel和sql的问题

group by laravel和sql的问题
EN

Stack Overflow用户
提问于 2019-05-16 23:56:59
回答 2查看 69关注 0票数 0

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

代码语言:javascript
运行
复制
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可以做到这一点?

提前感谢您:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-17 04:31:51

我会将withCount()select(DB::raw())结合使用,如下所示:

代码语言:javascript
运行
复制
$products = Product::withCount(['invoices as quantity' => function ($query) {
    $query->select(DB::raw('sum(quantity)'));
}])->get();

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

代码语言:javascript
运行
复制
$quantity = $products->first()->quantity;
票数 2
EN

Stack Overflow用户

发布于 2019-05-17 02:00:23

你需要更新你的模型关系来实现这一点。

型号:

InvoiceProduct模型

代码语言:javascript
运行
复制
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
}

控制器:

代码语言:javascript
运行
复制
$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');
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56172447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档