当我运行以下代码时,我正确地得到了附加点的总和。
User::withCount([
'points' => function ($q) {
$q->select(DB::raw("SUM(points)"));
},
])
但是当我使用selectRaw("SUM(points)")
而不是select(DB::raw("SUM(points)"))
时,Laravel会返回行数,而不是总和。好像该功能根本没有运行。是什么给了什么?
这是Eloquent提出的MySQL查询
#With DB::raw
"select `users`.*, (select SUM(points) from `user_points` where `users`.`user-id` = `user_points`.`user-id`) as `points_count`
from `users`
order by `points_count` desc"
#With selectRaw
"select `users`.*, (select count(*) from `user_points` where `users`.`user-id` = `user_points`.`user-id`) as `points_count`
from `users`
order by `points_count` desc"
为什么DB::raw
和selectRaw
会在上面的示例中返回不同的结果?
答案 0 :(得分:1)
它们几乎相同但selectRaw
允许绑定。看源代码:
// Line 232, /Illuminate/Database/Query/Builder.php
public function selectRaw($expression, array $bindings = [])
{
$this->addSelect(new Expression($expression));
if ($bindings) {
$this->addBinding($bindings, 'select');
}
return $this;
}
// Line 835 /Illuminate/Database/Connection.php
public function raw($value)
{
return new Expression($value);
}
基于方法签名
// You can do bindings with selectRaw()
->selectRaw('complex_thing(column_name, ?)', [123]);
// but there's not a way to do bindings with DB::raw()
->select(DB::raw('no_bindings_allowed('fixed', 'values', 42)');
您可以手动将值插入上面的DB::raw()
字符串中,但您需要进行验证以确保无法进行代码注入。希望你能理解。
答案 1 :(得分:1)
您会收到不同的查询,因为select()
会替换所选列,而selectRaw()
会添加所选列。
因此select(DB::raw('SUM(points)'))
取代了默认的count(*)
。