【问题标题】:Collection Where LIKE Laravel 5.4收藏 LIKE Laravel 5.4 的地方
【发布时间】:2017-10-21 13:42:14
【问题描述】:

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

我的数据是:

collect($products)->where('name', 'LIKE', '%'. $productName . '%');

Laravel 不支持集合中的 where like。我正在考虑使用

collect($products)->filter( function () use ($productName) {    
    return preg_match(pattern, subject);
});

但我不知道该怎么做。 TY

【问题讨论】:

    标签: laravel


    【解决方案1】:

    在集合上,您可以使用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 或您需要匹配字符串的任何内容。

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

    【讨论】:

    • 我推荐使用stripos(),而不是stristr(),消耗更少的内存。
    【解决方案2】:

    另一种选择是在查询数据库(首先获取集合)时添加WHERE LIKE 子句,而不是获取所有项目然后过滤。

    例如:

    $products = Product::where('name', 'like', '%match%')->get();
    

    因为您仍在处理数据库和 SQL(还不是集合),所以它可以工作。

    【讨论】:

    • 他正在处理一个收藏。最坏的情况是遍历所有内容并匹配结果。
    猜你喜欢
    • 2017-10-26
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 2017-09-11
    • 1970-01-01
    相关资源
    最近更新 更多