简体   繁体   English

如何使用Laravel查询构建器合并来自同一表的两个查询

[英]How to combine two queries from the same table using Laravel query builder

From this sales table, I created 2 queries. 从该销售表中,我创建了2个查询。

Sale::where(branch_id', 1)->select('*', DB::raw('SUM(amount) as amount))->groupBy('date')->get()

Sale::where(branch_id', 2)->select('*', DB::raw('SUM(amount) as amount))->groupBy('date')->get()

I want to combine the two queries... 我想结合两个查询...

to achieve this 为达到这个

在此处输入图片说明

Here's my sales table 这是我的销售表

实际销售表

Since they're both identical except for an integer, you could simply do this: 由于除了整数外,它们都相同,因此您可以简单地这样做:

Sale::whereIn('branch_id', [1, 2])->...

... and let the rest of the query stay the same. ...,并使其余查询保持不变。

I think what you're looking for in raw SQL is this: 我认为您在原始SQL中寻找的是:

SELECT 
    `date`,
    SUM(IF(branch_id = 1, amount, 0)) as 'Branch 1',
    SUM(IF(branch_id = 2, amount, 0)) as 'Branch 2',
    SUM(amount) as 'Total'
FROM
    branches
WHERE
    branch_id IN (1,2)
GROUP BY
    `date`;

Unfortunately you can't do most of this with querybuilder, so you'll need to do it with DB::raw() , something like this: 不幸的是,您不能使用querybuilder来完成大多数操作,因此您需要使用DB::raw()来完成此操作,如下所示:

Sale::whereIn(branch_id', [1,2])->
        select('date',
                DB::raw("
                    SUM(IF(branch_id = 1, amount, 0)) as 'Branch 1',
                    SUM(IF(branch_id = 2, amount, 0)) as 'Branch 2',
                    SUM(amount) as amount
                    ")
                )->groupBy('date')->get();

I haven't tested this in Laravel so it may be slightly off, but it should get you close. 我还没有在Laravel中测试过它,所以它可能会稍微有些偏离,但它应该使您接近。

Sample fiddle. 样品小提琴。

Try This. 尝试这个。

DB::table('Sale')->whereIn('branch_id',[1,'2])->get(); DB ::表( '销售') - >其特征在于,( 'branch_id',[1,'2]) - >得到();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM