首页 > 解决方案 > 如果在 where 组合到 laravel 之间的子句收集

问题描述

情况:

$post_1 = 'john'; 
$post_2 = 30;

$arr = array(['name'=>'john','number'=>70],['name'=>'clark','number'=>50]); 
$collection = collect($arr);

if($post_1 == 'john')
{
     $collection->where('name',$post_1); 
}
if($post_2 == 70)
{
     $collection->where('number',$post_2);
}
var_dump($collection->all());

但这不起作用。我想包含过滤器,但这取决于是否存在帖子参数。

标签: laravelcollect

解决方案


我认为你可以使用when

$result= $collection->when(($post_1=="john"), function ($collection)use($post_1) {

        return $collection->where('name',$post_1);

    })->when(($post_2 == 70), function ($collection)use($post_2) {

        return $collection->where('number',$post_2);

    })->all();


dd($result);

或者

$collection->when(($post_1=="john"), function ($collection)use($post_1) {

            return $collection->where('name',$post_1);

        })->when(($post_2 == 70), function ($collection)use($post_2) {

            return $collection->where('number',$post_2);

        });
    
    
    dd($collection->all());

参考:https ://laravel.com/docs/8.x/collections#method-when


推荐阅读