Laravel 5.5 Collection where like

好久不见. 提交于 2021-02-05 11:13:24

问题


i am filtering data using collections. But i need to use like method. I had tried to write like this : ('name', 'LIKE', '%value%') but it did not work.

Here is my method :

protected function filterData(Collection $collection, $transformer) {
    foreach (request()->query() as $query => $value) {
        $attribute = $transformer::originalAttribute($query);

        if (isset($attribute, $value)) {
            $collection = $collection->where($attribute, $value);
        }
    }

    return $collection;
}

回答1:


The 1st question is whether you really know what you are doing. If you take data from database and then filter it just to take some elements it's definitely not the best way because you can take from database for example 100000 records just to finally have only 2 elements and it will kill your application performance.

But assuming you really want to filter using Support collection, there is no where together with LIKE because you are just filtering an array. If you want to use something similar to like instead of:

$collection = $collection->where('name', $value);

you can use:

$collection = $collection->reject(function($element) use ($value) {
    return mb_strpos($element->name, $value) === false;
});

depending on what you really have in collection instead of $element->name you might need to use $element['name']



来源:https://stackoverflow.com/questions/47413022/laravel-5-5-collection-where-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!