过滤雄辩收藏 [英] Filtering Eloquent Collection
本文介绍了过滤雄辩收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试根据多个值的任意组合向下过滤集合对象。这是我所知道的。没有发生。任何线索给我?
Trying to filter a collection object down based upon any combination of multiple values. This is as far as I've got. Not happening. Any clues for me?
public function search()
{
$posts = Posting::all();
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($country_id) && $country_id>0 )
{
return $post->where('country_id','=',$country_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($province_id) && $province_id>0 )
{
return $post->where('province_id','=',$province_id);
}
})->values();
return $posts;
}
任何帮助赞赏。
推荐答案
首先,您需要从您的过滤器
中的关闭返回有意义的内容:
First off, you need to return something that makes sense from the closure in your filter
:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})
上面返回 Eloquent\Builder
对象,其中被评估为 true
,所以..真的没有意义。
Above returns Eloquent\Builder
object, which is evaluated to true
, so.. it really doesn't make sense.
这是什么您需要:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->type_id == $type_id; // bool
}
})
使用这样的代码,您将过滤该集合。 $ posts
现在将只保留与该关闭中的语句相匹配的项目。
With such code, you will filter the collection. $posts
now will hold only those items, that match the statement in that closure.
这篇关于过滤雄辩收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文