Laravel 5.5集合在哪里像 [英] Laravel 5.5 Collection where like
问题描述
('name','LIKE','%value%')
,但是它没有用.这是我的方法:
受保护的函数filterData(Collection $ collection,$ transformer){foreach(request()-> query()as $ query => $ value){$ attribute = $ transformer :: originalAttribute($ query);如果(isset($ attribute,$ value)){$ collection = $ collection-> where($ attribute,$ value);}}返回$ collection;}
第一个问题是您是否真的知道自己在做什么.如果您从数据库中获取数据然后仅对其进行过滤以获取某些元素,那绝对不是最好的方法,因为您可以从数据库中获取100000条记录,而最终仅拥有2个元素,这会破坏应用程序的性能.
但是,假设您确实要使用Support集合进行过滤,那么LIKE就没有地方了,因为您只是在过滤数组.如果您想使用类似like之类的东西代替
: $ collection = $ collection-> where('name',$ value);
您可以使用:
$ collection = $ collection->拒绝(function($ element)use($ value){返回mb_strpos($ element-> name,$ value)=== false;});
取决于您实际拥有的内容而不是 $ element-> name
,您可能需要使用 $ element ['name']
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;
}
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']
这篇关于Laravel 5.5集合在哪里像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!