如何为 DB::raw 设置绑定?



在 Laravel 5.7 中,我有一个这样的 Eloquent 查询:

return User::findOrFail($userId)
->dogs()
->setBindings(['', '', '', '', $userId])
->get([
'name',
DB::raw('coalesce(birth_year, ?) <> ? as birth_year')
DB::raw('coalesce(breed, ?) <> ? as breed')
]);

这是一个稍微简化的示例,但总的来说,我需要的是将绑定传递给DB::raw()

我的例子有效,但我不喜欢我需要手动覆盖应该自然来自user-dogs关系$userId的事实。另外,我不喜欢所有绑定都在一起。

有没有更好的方法来使用DB::raw,就像在我的示例中一样?我知道有一个selectRaw,但我不想选择所有列

selectRaw添加一个原始选择表达式。它不会选择所有原始列。它还有第二个用于绑定的参数,因此您可以使用它:

return User::findOrFail($userId)
->dogs()
->select('name')
->selectRaw('coalesce(birth_year, ?) <> ? as birth_year', ['', ''])
->selectRaw('coalesce(breed, ?) <> ? as breed', ['', $userId])
->get();

最新更新