MySQL Laravel Eloquent 忽略大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21213490/
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
Laravel Eloquent Ignore Casing
提问by Lpc_dark
I am trying to run a query using Eloquent the $vars['language'] is in lower case but the language column is not necessarily in lower case. How can i do this search using eloquent but still have the lower case in the query
我正在尝试使用 Eloquent 运行查询 $vars['language'] 是小写的,但语言列不一定是小写的。我如何使用 eloquent 进行此搜索,但在查询中仍然使用小写
Item::where('language', $vars['language'])
What i want to do is this even though i can't find anywhere how to do this
我想做的是即使我在任何地方都找不到如何做到这一点
Item::where('LOWER(language)', $vars['language'])
so that they are both in lowercase and then i can get them to match.
这样它们都是小写的,然后我可以让它们匹配。
回答by Margus Pala
Use whereRaw with parameter bindingto sanitize your whereRaw statement:
使用 whereRaw 和参数绑定来清理你的 whereRaw 语句:
$term = strtolower($vars['language']);
Item::whereRaw('lower(language) like (?)',["%{$term}%"])->get();
Prev answerIn some dabases you can use operator ilike
in your where. For example
上一个答案在某些数据库中,您可以ilike
在您的位置使用运算符。例如
Item::where('language', 'ilike', $vars['language'])->get();
All available operators are:
所有可用的运算符是:
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
);
Edit: ilike
is case-insensitive like
.
编辑:ilike
不区分大小写like
。
回答by igorsantos07
回答by Patrick.SE
The filter()
collection method can be useful if you are trying to find a laravel-based solution :
的filter()
,如果你正在努力寻找一个基于laravel的解决方案收集方法可能是有用的:
// $this refers to an instance of an eloquent User Model
$name = 'BiLbo baGGings';
return $this->contactInformation->filter(function($value, $key) use($name) {
if(strtolower($value->name) == strtolower($name)) {
return $value;
}
});