为什么不能在预加载查询中使用 groupBy() - Laravel

Why is it not possible to use groupBy() in an eager loading query - Laravel

错误异常:

stripos() expects parameter 1 to be string, object given

对于with()方法中的groupBy()调用

$user = User::with([
    'pricelists' => function($query) {
        $query->groupBy(function($var) {
            return Carbon::parse($var->pivot->created_at)->format('m');
        });
     }
])->where('id', $id)->get();

我已经看到一些帖子在谈论如何解决这个问题,并且不能在 eloquent 中使用 groupBy() 但我真的不明白为什么...

要明确:

UserPricelist 模型与默认的 timestamps() 方法建立了多对多关系。我正在尝试按从当前用户下载的月份对下载的价目表进行分组。

经过几次尝试,我刚刚从 with() 方法中删除了上面显示的 => function($query... 语句,并只留下 with(['pricelist']) 来获取所有数据集并尝试了这个:

$user->pricelists = $user->pricelists->groupBy(function($var) {
    return Carbon::parse($var->pivot->created_at)->format('m');
});
return $user->pricelists;

它工作正常并且 returns 每个月都有一个包含多个数组的数组......但是返回它是这样的:

return $user;

returns 只有 1 个包含所有条目的数组...我现在真的不明白它背后的意义...

您在提供的两个代码中使用的两个groupBy()方法是完全不同的方法。

你在回调中使用它的第一个 groupBy() 实际上是由 $query 调用的,它是一个 query builder object. The groupBy() here is used to add SQL GROUP BY Statement into the query. And as per the documentation,它只接受字符串变量作为参数。

第二个代码中的 groupBy()$user->pricelists 调用,它是 laravel eloquent collection. The groupBy() method here is actually from the base collection class and is used to group the items inside the collection into multiple collections under the different key defined by the parameter passed to the function. Please read the documentation here.

对于您的情况,第二个 groupBy() 是您应该使用的,因为您计划使用回调并将允许您使用更复杂的逻辑。