喜欢 Laravel 5.4 的集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44103711/
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
Collection Where LIKE Laravel 5.4
提问by Rbex
I know collection doesn't support where LIKE but how can I achieve this.
我知道收藏不支持 LIKE 的位置,但我怎样才能做到这一点。
collect($products)->where('name', 'LIKE', '%'. $productName . '%');
Laravel doesn't support where like in the collection. I'm thinking to use
Laravel 不支持集合中的 where 。我想用
collect($products)->filter( function () use ($productName) {
return preg_match(pattern, subject);
})
but I don't know how to do it. TY
但我不知道该怎么做。泰
回答by aljo f
On a collection you can use the filter($callback_function)
method to select items in the collection. Pass in a callback function that returns true
for every item that should be returned.
在集合上,您可以使用该filter($callback_function)
方法来选择集合中的项目。传入一个回调函数,该函数true
为每个应该返回的项目返回。
In your case you can use the stristr()
function to emulate a LIKE
operator, like this:
在您的情况下,您可以使用该stristr()
函数来模拟LIKE
运算符,如下所示:
collect($products)->filter(function ($item) use ($productName) {
// replace stristr with your choice of matching function
return false !== stristr($item->name, $productName);
});
Just replace stristr
with preg_match
or what ever you need to match strings.
只需替换stristr
为preg_match
或您需要匹配字符串的任何内容。
This will return the collection in its original structure minus the non matching items.
这将返回原始结构中的集合减去不匹配的项目。
回答by Drown
Another option is to add the WHERE LIKE
clause when you're querying the database (fetching the collection in the first place) instead of getting all items and then filtering down.
另一种选择是WHERE LIKE
在查询数据库时添加子句(首先获取集合),而不是获取所有项目然后过滤。
For example :
例如 :
$products = Product::where('name', 'like', '%match%')->get();
Since you're still dealing with the database and SQL (and not yet a collection), that works.
由于您仍在处理数据库和 SQL(还不是集合),因此可以使用。