【问题标题】:Laravel query builder; get distinct rows with sumsLaravel 查询生成器;用总和获得不同的行
【发布时间】:2021-08-30 05:40:14
【问题描述】:

假设我们有一个名为 BoxContents 的 SQL 表,其中每一行包含 id、boxID、itemID 和数量。

只有唯一的值是 id。我需要输入 boxID 并获取 itemID 的列表/数组及其 TOTAL 数量;

示例: 在 BoxContents 表中:

id boxID itemID quantity
1 foo banana 5
2 foo monkey 1
3 bar bomb 2
4 foo banana 5
5 bar fuse 2
6 bar banana 5
7 foo banana 5

查询box foo时的结果:

['banana'=>15, 'monkey'=>1]

查询框栏时的结果:

['bomb'=>2, 'fuse'=>2, 'banana'=>5]

我将如何进行查询?

DB::table('BoxContents')
    ->where('boxID', 'foo')
    ->select('itemID', SUM('quantity'))
    ->distinct();

是我目前得到的,但SUM()显然不被select()接受

这个可以吗?

【问题讨论】:

    标签: php laravel laravel-8 laravel-query-builder


    【解决方案1】:

    您可以通过selectRaw()/DB::raw()

    DB::table('BoxContents')
        ->where('boxID', 'foo')
        ->select('itemID', DB::raw("SUM('quantity')"))
        ->distinct();
    

    【讨论】:

    • 谢谢!不知道DB::raw可以这样用,以后会派上用场的!另外,感谢您对我的问题的样式:)
    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 2015-12-14
    • 2020-12-25
    • 2015-04-06
    • 1970-01-01
    • 2021-02-18
    • 2015-12-13
    • 1970-01-01
    相关资源
    最近更新 更多