在Laravel中使用Eloquent ORM使用LIKE执行数据库搜索

Jon*_*han 90 orm laravel eloquent sql-like

我想使用Eloquent的活动记录构建来构建搜索查询,但它将是一个LIKE搜索.我找到了User::find($term)或者User::find(1),但这并没有产生类似的声明.我不是在寻找一个直接的答案,但是如果有人能够至少给我一个指导,那就太好了!

Joe*_*son 231

您可以使用以下语法使用LIKE执行数据库查找:

Model::where('column', 'LIKE', '%value%')->get();
Run Code Online (Sandbox Code Playgroud)

  • 它很好,我怎样才能从相关模型中搜索? (2认同)

Yar*_*lav 64

如果您需要经常使用LIKE,可以稍微简化一下问题.可以在继承Eloquent ORM的模型中创建像()这样的自定义方法:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}
Run Code Online (Sandbox Code Playgroud)

那么你可以这样使用这个方法:

User::like('name', 'Tomas')->get();
Run Code Online (Sandbox Code Playgroud)


dea*_*nde 28

仅供参考,运营商列表(包含喜欢和所有其他运营商)在代码中:

/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

protected $operators = array(
    '=', '<', '>', '<=', '>=', '<>', '!=',
    'like', 'not like', 'between', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
);
Run Code Online (Sandbox Code Playgroud)

免责声明:

Joel Larson的回答是正确的.得到了我的upvote.

我希望这个答案可以通过Eloquent ORM更多地了解可用的内容(直接指向人们).虽然到文档的链接会越好,这种联系已经证明自己是难以捉摸的.


小智 17

使用双引号而不是单引号,例如:

where('customer.name', 'LIKE', "%$findcustomer%")
Run Code Online (Sandbox Code Playgroud)

以下是我的代码:

public function searchCustomer($findcustomer)
{
    $customer = DB::table('customer')
                  ->where('customer.name', 'LIKE', "%$findcustomer%")
                  ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                  ->get();

    return View::make("your view here");
}
Run Code Online (Sandbox Code Playgroud)