laravel - 喜欢 Laravel 5.4 的集合

标签 laravel

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

我的数据是:
enter image description here

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);
});

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

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

关于laravel - 喜欢 Laravel 5.4 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44103711/

相关文章:

php - 在 Laravel 中为多行插入中的字段设置固定值

php - Laravel Forge - Composer 问题

php - 是否可以在App :before filter in Laravel?中返回

php - 用新值替换数组值

php - Laravel Ajax - 即使数据库行不存在也会成功执行

php - 非静态方法不应该静态调用,假设 $this 来自不兼容的上下文 -Laravel 5.2

laravel - Blade中的Section和Stack有什么区别?

php - 获取我的 laravel 网站的所有链接以获取站点地图

php - 从一张 MySQL 表中删除父表和所有子表

database - 如何获取刚刚插入的最新记录的ID?