Laravel执行StockOut关联分组查询报array + App\StockOut类型不支持错误
报错根因
直接定位到报错触发点:map回调里的这行代码
] + $group->first();
PHP的+运算符仅支持数组与数组的合并操作,右侧操作数是App\StockOut模型实例、不是数组,自然抛出Unsupported operand types类型错误。
为什么相同代码在其他项目能正常跑
核心差异是Laravel框架版本不同:
- 旧版本Laravel(5.x部分版本)对模型实例的隐式转换做了兼容,碰到数组+模型的写法会自动将模型转成数组再执行合并
- Laravel 7及以上版本移除了这种隐式兼容,
$collection->first()直接返回模型对象,碰到这种写法会直接抛出类型错误
快速验证方法
- 在map回调里临时加调试代码,确认返回值类型:
->map(function ($group) { // 临时调试 dd(get_class($group->first()), is_array($group->first())); // ...原有代码 })
- 分别在两个项目执行
php artisan --version,确认Laravel版本差
可落地的修复方案
方案1:手动将模型转数组后再合并
把原有直接拼接的逻辑,改成先把模型实例转成数组,再做键值替换:
->map(function ($group) { // 把首个模型实例转成基础数组 $base = $group->first()->toArray(); // 用array_replace替换需要自定义的键值,避免原数据被错误覆盖 return array_replace($base, [ 'id_stock_ins' => $group->pluck('stock_ins.id_stock_in')->join(','), 'id_stock_outs' => $group->pluck('id_stock_outs')->join(',') ]); })
注意:这里不能用
array_merge,因为关联键重复时array_merge会覆盖前面的值,和原有+运算符的行为不一致
方案2:按需构造返回结构,跳过类型拼接
如果不需要保留模型上的全部属性,直接从组内提取需要的字段组装结构,避免跨类型运算:
->map(function ($group) { $firstRow = $group->first(); return [ // 按需从模型实例取需要保留的字段 'date_of_stock_out' => $firstRow->date_of_stock_out, 'quantity' => $firstRow->quantity, 'id_stock_ins' => $group->pluck('stock_ins.id_stock_in')->join(','), 'id_stock_outs' => $group->pluck('id_stock_outs')->join(','), 'stock_in' => $firstRow->stock_ins ]; })
内容的提问来源于stack exchange,提问作者ProLuck
相关产品推荐
相关产品推荐

