Laravel eloquent 尝试使用 sum 时错误期望参数 1 为字符串

Laravel eloquent error expects parameter 1 to be string when trying to use sum

我使用了这个查询:

Product::whereId($item->id)->sum(function ($row) {
                return $row->quantity * ($row->variable ?? 1);
            });

但是我得到了这个错误:

production.ERROR: stripos() expects parameter 1 to be string, object given

我想得到 $row->quantity * $row->variable 的结果作为总和,但是 $row->variable 中的一些是空的,所以我使用了 ($row->variable ?? 1).

是的,它会抛出异常,因为您必须使用字符串而不是函数(闭包)

以这个为例

Product::selectRaw("sum(quantity * variable)")->whereId($item->id)->get();

我使用 get() 在 sum 之前获取集合,我的问题解决了。

所以我将代码更改为:

Product::whereId($item->id)->get()->sum(function ($row) {
                return $row->quantity * ($row->variable ?? 1);
});

运行 collection 上的求和函数如果你的 collection 很小就可以了

但是如果你有一个很大的collection,比如说你里面有2000件物品,那么在mysql中计算总和会是一个不错的选择

在您的代码中,您首先从 DB 中获取结果,然后 运行 在 php 中而不是在 mysql

中 collection 的求和运算

但结果是一样的

直到你不得不面对大collection才放心

我建议通过一些条件聚合直接在数据库层执行这样的求和操作

Product::whereId($item->id)
       ->sum(\DB::raw('quantity * (case when variable > 0 then variable else 1 end)'));

上述方法有两个主要好处

  • 让您的 logic/code 尽可能简单,这样当您可以直接从数据库服务器,这是数据库处理的非常常见的操作。
  • 使用收集辅助方法时不需要额外的循环和计算