我有以下SQL查询:
return User::where("users.id", $id)
->select(array('rating.rate', User::raw('count(offers.id) AS ofrs, count(announcements.id) as appts')))
->join('announcements', 'users.id', '=', 'announcements.user_id')
->join('offers', 'users.id', '=', 'offers.user_id')
->join('rating', 'users.id', '=', 'rating.user_id')
->group_by('ofrs')
->get();
它给了我一个错误:
Builder.php第2508行中的BadMethodCallException:调用undefined 方法Illuminate \ Database \ Query \ Builder :: group_by()
为什么不按分组工作?
同样我尝试的方式:
return User::where("users.id", $id)
->selectRaw('rating.rate, count(offers.id) AS ofrs, count(announcements.id) as appts')
->groupBy('appts')
->groupBy('ofrs')
->join('announcements', 'users.id', '=', 'announcements.user_id')
->join('offers', 'users.id', '=', 'offers.user_id')
->join('rating', 'users.id', '=', 'rating.user_id')
->get();
结果:
SQLSTATE[42000]: Syntax error or access violation: 1056 Can't group on 'appts'
我在SQL中直接编写了SQL查询:
select rating.rate, COUNT(offers.id) AS ofrs, COUNT(announcements.id) as appts from `users` left join `announcements` on `users`.`id` = `announcements`.`user_id` left join `offers` on `users`.`id` = `offers`.`user_id` left join `rating` on `users`.`id` = `rating`.`user_id` where `users`.`id` = 1
它有效,按型号不是:
return User::where("users.id", $id)
->selectRaw('rating.rate, COUNT(offers.id) AS ofrs, COUNT(announcements.id) as appts')
->leftJoin('announcements', 'users.id', '=', 'announcements.user_id')
->leftJoin('offers', 'users.id', '=', 'offers.user_id')
->leftJoin('rating', 'users.id', '=', 'rating.user_id')
->get();
这项工作:
return User::where("users.id", $id)
->selectRaw('rating.rate, COUNT(offers.id) AS ofrs, COUNT(announcements.id) AS appts')
->leftJoin('announcements', 'users.id', '=', 'announcements.user_id')
->leftJoin('offers', 'users.id', '=', 'offers.user_id')
->leftJoin('rating', 'users.id', '=', 'rating.user_id')
->groupBy('rating.rate')
->get();
答案 0 :(得分:2)
答案 1 :(得分:1)
您需要了解SQL的工作原理。您无法按计数别名进行分组。您正在寻找的可能是三个查询或三个关系。
您应该在用户上为公告创建关系,第二个用于提供,第三个用于评级。
比您User::find($id)->announcements->count()
,User::find($id)->offers->count()
和User::find($id)->ratings->count()
或者您可以使用您的Fluent方式:
return User::find($id)
->leftJoin('announcements', 'users.id', '=', 'announcements.user_id')
->count();