2014-07-26 40 views
0

试图根据多个值的任意组合过滤集合对象。这是我所知道的。没有发生。任何线索对我来说?过滤Eloquent集合

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

赞赏任何帮助。

+0

你能显示什么Input :: all()返回? – Jazerix

+0

宣布$ post在哪里?你确定你在返回结果时不是指$ post? – Jazerix

+0

$ post是关闭参数的名称:'$ posts = $ posts-> filter(function($ post)'。 – RSAdmin

回答

0

首先,你应该确认id大于0,如果提供的话。你不应该手动检查。

但无论如何,你为什么要使用过滤器,当你可以直接使用佞(我省略了ID为大于0的检查):

$type_id  = Input::get('type_id'); 
$country_id = Input::get('country_id'); 
$province_id = Input::get('province_id'); 

$query = Posting::query(); 

if (! empty($type_id))  $query->whereTypeId($type_id); 

if (! empty($country_id)) $query->whereCountryId($country_id); 

if (! empty($province_id)) $query->whereProvinceId($province_id); 

return $query->get(); 
+0

当我尝试使用此代码modifyin g到'$ posts = $ query-> get()'$ posts的最后一行总是未定义的。哦,坚果。我的数据实际上是嵌套的:我想要过滤的字段在$ posting-> profile-> type_id等现在我该怎么办? $ query-> profile-> whereTypeId($ type_id)? – RSAdmin

+0

请考虑看看后续问题:http://stackoverflow.com/questions/24976917/eloquent-filtering-of-nested – RSAdmin

+0

我在其他帖子中回复 – Kousha

0

首先,你需要返回这是令从封闭感的filter

$posts = $posts->filter(function($post) 
{ 
    if(!empty($type_id) && $type_id>0) 
    { 
    return $post->where('type_id','=',$type_id); 
    } 
}) 

以上的回报Eloquent\Builder对象,进行评估,以true,所以..它真的没有意义。

这是你所需要的:

$posts = $posts->filter(function($post) 
{ 
    if(!empty($type_id) && $type_id>0) 
    { 
    return $post->type_id == $type_id; // bool 
    } 
}) 

有了这样的代码,你将过滤收集。 $posts现在将只保存那些符合该封闭语句的项目。