Laravel雄辩查询,主查询和子查询回调函数上的链接groupBy
我试图查询项目模型&按groupId分组,然后按用户id进一步分组&合计销售数量,但出现错误。下面是我的代码Laravel雄辩查询,主查询和子查询回调函数上的链接groupBy,laravel,eloquent,Laravel,Eloquent,我试图查询项目模型&按groupId分组,然后按用户id进一步分组&合计销售数量,但出现错误。下面是我的代码 $items = Item::where('sold', true)->get()->groupBy('groupId', function ($query){ $query->select(DB::raw('userid,sum(sales_count) as total_sales_count'))->groupBy('userid');
$items = Item::where('sold', true)->get()->groupBy('groupId', function ($query){
$query->select(DB::raw('userid,sum(sales_count) as total_sales_count'))->groupBy('userid');
})->get();
我得到的错误如下:
Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in
预期结果雄辩\收集:
[
17558 => [
[
"userid" => "2"
"total_sales_count" => "3"
],
[
"userid" => "4"
"total_sales_count" => "1"
],
],
18647 => [
[
"userid" => "5"
"total_sales_count" => "6"
],
[
"userid" => "7"
"total_sales_count" => "4"
],
]
]
模型结构:
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->integer('userid');
$table->integer('sales_count')->default(1);
$table->string('groupId')->nullable();
$table->boolean('sold')->default(true);
$table->timestamps();
});
您的查询应该是这样的-
$item = Item::where('sold', true)
->select('user_id', DB::raw('sum(items.sales_count) as total_sales_count'))
->groupBy('groupId')
->get();
删除第一个get,然后tryI尝试了该操作,但出现了以下错误:stripos希望参数1为字符串,object givenI尝试了该操作,但出现了以下错误:``SQLSTATE[42000]:语法错误或访问冲突:SELECT列表的1055表达式1不在GROUP BY子句中,并且包含未聚合的列“mydb.items.user_id”,该列在功能上不依赖GROUP BY子句中的列;这与sql不兼容。\u mode=only\u full\u group\u by sql:select user\u id,sumsales\u count as total\u sales\u count from items group by groupId``你能分享你的表结构吗?我已经更新了问题,将模型结构包括在内。