Php 如何为DB::raw设置绑定?
在Laravel 5.7中,我有一个雄辩的问题,如下所示:Php 如何为DB::raw设置绑定?,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,在Laravel 5.7中,我有一个雄辩的问题,如下所示: return User::findOrFail($userId) ->dogs() ->setBindings(['', '', '', '', $userId]) ->get([ 'name', DB::raw('coalesce(birth_year, ?) <> ? as birth_year') DB::raw('coalesc
return User::findOrFail($userId)
->dogs()
->setBindings(['', '', '', '', $userId])
->get([
'name',
DB::raw('coalesce(birth_year, ?) <> ? as birth_year')
DB::raw('coalesce(breed, ?) <> ? as breed')
]);
返回用户::findOrFail($userId)
->狗()
->setBindings(['','','',$userId])
->得到([
“姓名”,
DB::raw('合并(出生年份),作为出生年份')
DB::raw(‘结合(品种?)?作为品种’)
]);
这是一个稍微简化的示例,但我通常需要将绑定传递到DB::raw()
我的示例是可行的,但我不喜欢这样一个事实,即我需要手动覆盖$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();
返回用户::findOrFail($userId)
->狗()
->选择('名称')
->选择RAW('合并(出生年份),作为出生年份,['',])
->selectRaw('coalesce(breed,?)as breed',[''$userId])
->get();
你能发布你的狗
关系函数来了解用户
和狗
之间的数据库关系吗?这种关系与我的问题无关,但如果你需要,它是多对多的。谢谢。在你发帖之前我就是这么做的。很高兴知道我们同意:)