【问题标题】:how to filter collection in laravel by like如何通过like过滤laravel中的集合
【发布时间】:2020-05-05 19:57:05
【问题描述】:

我想在 laravel 中按名称过滤一个集合,例如“%something%”,但其中的 like 在集合中不起作用 我该如何解决这个问题? 我写了这个方法,不适用于名称过滤器

protected function filterData(Collection $collection, $transformer)
{
    foreach (request()->query() as $query => $value) {
        $attribute = $transformer::originalAttribute($query);
        if (isset($attribute, $value)) {
            if ($attribute == 'name') {
                $collection = $collection->where($attribute,'LIKE' ,"%$value%"); // problem is here
            }
            $collection = $collection->where($attribute, $value);
        }
    }
    return $collection;
}

【问题讨论】:

标签: php mysql laravel eloquent


【解决方案1】:

您可以像这样过滤您的收藏:

$collection = $collection->filter(function ($item) use ($attribute) {
            return strpos($item->name, $attribute) !== false;
        });

如果您收到错误消息 Trying to get property 'name' of non-object,只需将 $item->name 更改为 $item['name']

【讨论】:

  • 此答案按预期工作。自 PHP8 起,str_contains 也可以使用。
【解决方案2】:

改成这个

$collection = $collection->where($attribute,'LIKE' ,"%".$value."%"); // 问题来了

【讨论】:

    猜你喜欢
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2018-05-07
    • 2021-03-02
    • 1970-01-01
    • 2016-07-25
    • 2020-08-10
    相关资源
    最近更新 更多