【问题标题】:How to set bindings for DB::raw?如何为 DB::raw 设置绑定?
【发布时间】:2019-03-23 18:47:16
【问题描述】:

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

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

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

【问题讨论】:

  • 能否贴出你的dogs关系函数来了解userdogs之间的数据库关系
  • 这个关系和我的问题没有任何关系,但是如果你需要它,它是多对多的。

标签: php laravel laravel-5 eloquent


【解决方案1】:

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

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

【讨论】:

  • 谢谢。在你发帖之前,我就是这么做的。很高兴知道我们同意:)
猜你喜欢
  • 2019-08-20
  • 2017-06-14
  • 2018-11-17
  • 2014-12-02
  • 1970-01-01
  • 2018-01-24
  • 2018-10-24
  • 2010-12-27
  • 2013-09-01
相关资源
最近更新 更多