laravel - 如果在 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());
但这不起作用。我想包含过滤器,但这取决于是否存在帖子参数。
解决方案
我认为你可以使用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());
推荐阅读
- php - 注册中 $_POST 的未定义索引错误
- r - R:shinyMobile - f7DatePicker 在 iPad 上不工作
- c# - 通过与 Activator.CreateInstance 的接口实例化的 C# 程序集对象的生命周期
- tensorrt - 显示一个 tensorflow UFF 模型的内容
- html - 当用户通过滚动到达页面末尾时启用按钮
- javascript - 用 html() 替换 div 元素
- java - Java:将 Map.keySet() 保存到 ArrayList 会引发 StackOverflowError
- typescript - 如何让热模块重新加载以在打字稿 monorepo 中工作
- azure-devops - Azure devops repo 使用 RestApi 从 repo 下载特定文件
- sql - 2表1结果,一个棘手的SQL