像Laravel 5.4一样的收藏 [英] Collection Where LIKE Laravel 5.4

查看:56
本文介绍了像Laravel 5.4一样的收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道集合不支持LIKE,但是我该如何实现.

I know collection doesn't support where LIKE but how can I achieve this.

我的数据是:

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

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

Laravel doesn't support where like in the collection. I'm thinking to use

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

            return preg_match(pattern, subject);
        })

但是我不知道该怎么做.TY

but I don't know how to do it. TY

推荐答案

在集合上,您可以使用 filter($ callback_function)方法选择集合中的项目.传递一个回调函数,该函数为应返回的每个项目返回 true .

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.

您可以使用 stristr() 函数来模拟 LIKE 运算符,如下所示:

In your case you can use the stristr() function to emulate a LIKE operator, like this:

collect($products)->filter(function ($item) use ($productName) {
    // replace stristr with your choice of matching function
    return false !== stristr($item->name, $productName);
});

只需将 stristr 替换为 preg_match 或匹配字符串所需的任何内容.

Just replace stristr with preg_match or what ever you need to match strings.

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

This will return the collection in its original structure minus the non matching items.

这篇关于像Laravel 5.4一样的收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆