Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 尝试使用sum时,Laravel eloquent错误期望参数1为字符串_Php_Laravel_Eloquent_Laravel 7 - Fatal编程技术网

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

Php 尝试使用sum时,Laravel eloquent错误期望参数1为字符串,php,laravel,eloquent,laravel-7,Php,Laravel,Eloquent,Laravel 7,我使用了这个查询: Product::whereId($item->id)->sum(function ($row) { return $row->quantity * ($row->variable ?? 1); }); 但我有一个错误: production.ERROR:stripos()要求参数1为字符串,对象为给定的 我想得到$row->quantity*$row->variable的结果作为总和,但是$r

我使用了这个查询:

Product::whereId($item->id)->sum(function ($row) {
                return $row->quantity * ($row->variable ?? 1);
            });
但我有一个错误:

production.ERROR:stripos()要求参数1为字符串,对象为给定的


我想得到
$row->quantity*$row->variable
的结果作为总和,但是
$row->variable
中的一些结果是空的,所以我使用了
($row->variable??1)
是的,它抛出异常,因为您必须使用字符串而不是函数(闭包)

举个例子

Product::selectRaw("sum(quantity * variable)")->whereId($item->id)->get();
我使用
get()
在求和之前获取集合并解决了我的问题

因此,我将代码更改为:

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

如果集合较小,则对集合运行sum函数即可

但是如果你有一个巨大的集合,比如说你有2000个项目,那么在mysql中计算总和将是一个不错的选择

在代码中,首先从DB中获取结果,然后在php中而不是在mysql中运行集合的求和操作

但结果是一样的


在您必须面对大型集合之前,不要担心它

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

Product::whereId($item->id)
       ->sum(\DB::raw('quantity * (case when variable > 0 then variable else 1 end)'));
上述方法有两个主要好处

  • 保持逻辑/代码尽可能简单,这样就不需要获取内存中的所有行(代码库),无论给定条件下的数据集是小还是大,只要您可以直接从数据库服务器获取数据,这是数据库要处理的一个非常常见的操作
  • 使用collection helper方法时不需要额外的循环和计算

谢谢,但我说过,
$row->variable
中的一些是空的。为什么我不能使用函数?当
$row->variable
为空时,我怎么能使用一些不乘法的东西呢?所以我得到了类的
对象illumb\\Database\\elount\\Collection无法在
转换为数字,我不能使用它!