【问题标题】:Laravel 5.1 Query ScopeLaravel 5.1 查询范围
【发布时间】:2015-10-11 19:11:52
【问题描述】:

这是我的范围代码:

public function scopeTest($query, $text, $usrId)
{
    if (trim($text) != "") {
        return $query->where("usrid", "=" ,"$usrId")->where("text1", "LIKE" ,"%$text%")->orWhere("text2", "LIKE" ,"%$text%");
    }else{
        return $query->where("usrid", "=" ,"$usrId");
    }
}

我无法构建此查询:

select * from table where usrid = $usrId and (text1 like '%$text%' or text2 like '%$text%');

因为“或”条件不能正常工作。

【问题讨论】:

    标签: php mysql laravel scope


    【解决方案1】:

    Use a closure to create a group:

    $query->where('usrid', $usrId)->where(function ($query) use ($text) {
       $like = "%{$text}%";
    
       $query->where('text1', 'LIKE', $like)->orWhere('text2', 'LIKE' ,$like); 
    });
    

    【讨论】:

    • 别忘了将$text变量引入作用域。
    • 虽然这是您的帖子,但我没有找到您上次编辑的令人信服的理由。我当时觉得这很冒犯,所以投了反对票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-16
    • 2017-01-07
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多