laravel collect 之间的 If 子句
If clauses between where composition to laravel collect
情况:
$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());
但这行不通。我想包括过滤器,但这取决于 post 参数是否存在。
我想你可以使用 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());
情况:
$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());
但这行不通。我想包括过滤器,但这取决于 post 参数是否存在。
我想你可以使用 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());