Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何为DB::raw设置绑定?_Php_Laravel_Laravel 5_Eloquent - Fatal编程技术网

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

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

在Laravel 5.7中,我有一个雄辩的问题,如下所示:

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();

你能发布你的
关系函数来了解
用户
之间的数据库关系吗?这种关系与我的问题无关,但如果你需要,它是多对多的。谢谢。在你发帖之前我就是这么做的。很高兴知道我们同意:)