收集LIKE Laravel 5.4

Rbe*_*bex 16 laravel

我知道收藏不支持LIKE,但我怎样才能做到这一点.

我的数据是: 在此输入图像描述

collect($products)->where('name', 'LIKE', '%'. $productName . '%');
Run Code Online (Sandbox Code Playgroud)

Laravel不支持集合中的位置.我正在考虑使用

collect($products)->filter( function () use ($productName) {

            return preg_match(pattern, subject);
        })
Run Code Online (Sandbox Code Playgroud)

但我不知道怎么做.TY

alj*_*o f 30

在集合上,您可以使用该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);
});
Run Code Online (Sandbox Code Playgroud)

只需更换stristrpreg_match或者你需要匹配字符串什么都.

这将返回原始结构中的集合减去不匹配的项目.

  • 我建议使用 `stripos()` 而不是 `stristr()`,它消耗更少的内存。 (3认同)