在 Laravel 中使用 Eloquent ORM 使用 LIKE 执行数据库搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13386774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Eloquent ORM in Laravel to perform search of database using LIKE
提问by Jonathan
I want to use Eloquent's active record building to build a search query, but it is going to be a LIKE search. I have found the User::find($term)
or User::find(1)
, but this is not generating a like statement. I'm not looking for a direct answer, but if someone could at least give me a direction to look in that'd be great!
我想使用 Eloquent 的活动记录构建来构建搜索查询,但它将是一个 LIKE 搜索。我找到了User::find($term)
or User::find(1)
,但这不会产生类似的语句。我不是在寻找直接的答案,但是如果有人至少可以给我一个查看的方向,那就太好了!
回答by Joel Larson
You're able to do database finds using LIKE with this syntax:
您可以使用 LIKE 和以下语法进行数据库查找:
Model::where('column', 'LIKE', '%value%')->get();
回答by Yaroslav
If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:
如果你需要经常使用LIKE,你可以把问题简化一点。可以在继承 Eloquent ORM 的模型中创建像 () 这样的自定义方法:
public function scopeLike($query, $field, $value){
return $query->where($field, 'LIKE', "%$value%");
}
So then you can use this method in such way:
那么你可以这样使用这个方法:
User::like('name', 'Tomas')->get();
回答by dean grande
FYI, the list of operators (containing likeand all others) is in code:
仅供参考,操作员列表(包含喜欢和所有其他人)在代码中:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
);
disclaimer:
免责声明:
Joel Larson's answer is correct. Got my upvote.
乔尔·拉森的回答是正确的。得到我的赞成票。
I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be farbetter, that link has proven itself elusive.
我希望这个答案能让更多人了解通过 Eloquent ORM 提供的内容(直接指出正确的人)。虽然到文档的链接会远越好,这种联系已经证明自己是难以捉摸的。
回答by Myint Thu Lwin
Use double quotes instead of single quote eg :
使用双引号代替单引号,例如:
where('customer.name', 'LIKE', "%$findcustomer%")
Below is my code:
下面是我的代码:
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");
}
回答by Sinan Eldem
If you do not like double quotes like me, this will work for you with single quotes:
如果你不喜欢像我这样的双引号,这对单引号也适用:
$value = Input::get('q');
$books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get();
return view('pages/search/index', compact('books'));