【问题标题】:orWhere giving unexpected result或在哪里给出意想不到的结果
【发布时间】:2015-08-12 10:07:28
【问题描述】:

我想搜索 lang_id = 1 的页面,我正在使用以下 laravel 查询

$result =  $this->where('lang_id', $this->langId );
$result->where('title', 'LIKE', '%'.$search.'%')
       ->orWhere('description', 'LIKE', '%'.$search.'%');
$result->get();

它也给了我 lang_id 不是 1 的页面。

如何解决?

【问题讨论】:

    标签: laravel laravel-4 eloquent laravel-5


    【解决方案1】:

    这是因为您构建查询以返回具有此 lang_id 和标题的所有记录,或者以某个搜索关键字开头的描述。这就是为什么你会得到另一个结果,因为其中一些不符合 lang_id 要求,但它们符合描述匹配。

    您需要正确地对 where 条件进行分组,如下所示:

    $result =  $this->where('lang_id', $this->langId )
    ->where(function ($query) use ($search) {
        $query->where('title', 'LIKE', '%'.$search.'%')->orWhere('description', 'LIKE', '%'.$search.'%')
    });
    $result->get();
    

    这等于:

    SELECT * FROM table WHERE lang_id = $lang_id AND (
        title LIKE '%$search%' OR description LIKE '%$search%'
    )
    

    【讨论】:

    • 感谢您的帮助仍然有一个错误我们需要通过 use $search 否则它会给出异常。
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2017-01-05
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多