我知道收藏不支持 LIKE 的位置,但我怎样才能做到这一点。
我的数据是:
collect($products)->where('name', 'LIKE', '%'. $productName . '%');
Laravel 不支持集合中的 where 。我想用
collect($products)->filter( function () use ($productName) {
return preg_match(pattern, subject);
})
但我不知道该怎么做。 TY
最佳答案
在集合上,您可以使用 filter($callback_function)
方法来选择集合中的项目。传入返回 true
的回调函数对于应该退回的每个项目。
在您的情况下,您可以使用 stristr()
模拟 LIKE
的函数运算符,像这样:
collect($products)->filter(function ($item) use ($productName) {
// replace stristr with your choice of matching function
return false !== stristr($item->name, $productName);
});
只需更换
stristr
与 preg_match
或者你需要什么来匹配字符串。这将返回原始结构中的集合减去不匹配的项目。
关于laravel - 喜欢 Laravel 5.4 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44103711/