【问题标题】:Laravel Where Clause ORLaravel Where 子句 OR
【发布时间】:2020-11-28 06:18:01
【问题描述】:

所以我正在为一个数据库查询编写一个 where 子句,我想支持多个可能的值,但我一直遇到错误:

我试试:

$post = Post::findOrFail($id);
$count= $post->Comments->Where([['status', 'New'], ['status', 'Replied']])->count();

但我收到此错误:

array_key_exists():第一个参数应该是字符串或 整数 Illuminate\Foundation\Bootstrap\HandleExceptions::handleError 供应商/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php:361

那么,我试试:

$post = Post::findOrFail($id);
$count= $post->Comments->Where('status', 'New')->orWhere('status', 'Replied')->count();

但我收到此错误:

方法 Illuminate\Database\Eloquent\Collection::orWhere 没有 存在。

根据我的阅读,这两种方法可以让多个 where 子句在您想要一个或另一个的地方出现,而不是 and。

作为记录,一个 where 子句如下:

$post = Post::findOrFail($id);
$count= $post->Comments->Where('status', 'New')->count();

按预期工作。

【问题讨论】:

    标签: laravel eloquent laravel-7


    【解决方案1】:

    你需要获取Builder,而不是Collection,所以不是

    $post->Comments
    

    你应该使用

    $post->Comments()
    

    所以这应该可以工作

    $count= $post->Comments()->Where([['status', 'New'], ['status', 'Replied']])->count();
    

    但是这种语法会将条件 2 与 AND 连接起来,而这个

    $count= $post->Comments()->Where('status', 'New')->orWhere('status', 'Replied')->count();
    

    OR

    【讨论】:

    • 确实,Collection 上不存在 orWhere() 方法
    【解决方案2】:

    你试过 whereIn 吗?

    $comments = $post->Comments();
    $comments->whereIn('status', ['ACTIVE', 'EXPIRED']);
    

    作品集..

    【讨论】:

      猜你喜欢
      • 2015-08-06
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      相关资源
      最近更新 更多