【问题标题】:Laravel Eloquent is performing query as an OR clause rather than AND which is intendedLaravel Eloquent 将查询作为 OR 子句而不是 AND 来执行
【发布时间】:2014-09-11 21:23:54
【问题描述】:

我正在尝试使用 Eloquent ORM 在 Laravel 4 中构建一个查询,该查询仅匹配条件中的所有字段。我有下面的代码,它目前返回的数据符合任何条件而不是所有条件,或者如果你愿意的话,而不是 AND。

    $names = Input::get('names');
    $company = Input::get('company');

    $contacts = Contact::where(function($query) use ($names, $tags, $type, $sector, $company)
    {
        if (!empty($names)) {
            $query->where('firstname', 'LIKE', "%{$names}%")
            ->orWhere('lastname', 'LIKE', "%{$names}%");
        }
        if (!empty($company)) {
            $query->where('company', 'LIKE', "%{$company}%");
        }
    })
    ->paginate(100);


    return View::make('index')->with('contacts', $contacts)->with('searchingFlag', $searchingFlag)->with('names', $names)->with('tags', $tags)->with('type', $type)->with('sector', $sector)->with('company', $company);

所以我相信,我在这里所做的只是说明结果必须匹配名称字段和公司字段中的任何一个(如果设置了任何一个),但如前所述,返回的结果匹配其中一个子句而不是两个子句。

谁能帮我找出问题所在?

谢谢

【问题讨论】:

    标签: php laravel orm laravel-4 eloquent


    【解决方案1】:
    if(!empty($names)) {
        $query->whereRaw('firstname LIKE "%{$names}%" OR lastname LIKE "%{$names}%" ');
        }
    

    【讨论】:

    • 谢谢,考虑过这一点,但想使用 ORM
    【解决方案2】:

    你需要嵌套 wheres:

    if (!empty($names)) {
        $query->where(function ($q) use ($names) {
          $q->where('firstname', 'LIKE', "%{$names}%")
           ->orWhere('lastname', 'LIKE', "%{$names}%");
        }
    }
    

    这将导致:

    SELECT ... WHERE (firstname like .. OR lasname like ..) AND company ...
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2014-09-27
    相关资源
    最近更新 更多