laravel - laravel 查询中的 if 条件
问题描述
有时有些变量为空,所以如何检查变量不为空并直接应用于查询
$fiter_products = DB::table('products')->DISTINCT('modalid')->DISTINCT('brandid')->select('rimdiameter','modalid','modalname1','modalname2','image1','brand','minprice','maxprice')->where('hubbore','>=',$centre_bore)->where('boltpattern',$boltptn)->where('rimdiameter', $diameter)->where('rimwidth', $width)->where('rimwidthfront', $frontwid)->where('construction', $construct)->where('modalname2', $color)->where('brand', $brand)->get();
有什么办法可以解决这个问题?
解决方案
您可以将另一个闭包作为第三个参数传递给when 方法。如果第一个参数评估为 false,则此闭包将执行。
$fiter_products = DB::table('products')
->DISTINCT('modalid')
->DISTINCT('brandid')
->select('rimdiameter','modalid','modalname1','modalname2','image1','brand','minprice','maxprice')
->when($centre_bore, function($query, $centre_bore) {
$query->where('hubbore','>=',$centre_bore);
})->when($boltptn, function($query, $boltptn) {
$query->where('boltpattern',$boltptn);
})...
推荐阅读
- python - 如何在 Python 中访问多个打开的 Excel 文件
- c# - Xamarin Forms - 从 ListView 和 Observable 集合中删除行
- ios - 如何提高使用 ZIPFoundation 解压缩文件的速度?
- python-3.x - 列表发生了变异,但我没有直接对其进行变异
- deep-learning - DeepLearning4J LSTM 网络的输入数据模型
- c# - 如何让 SQL Server 表存储一个列表?
- google-cloud-networking - 如何验证 Cloud CDN 响应是否是缓存命中(或来自 CDN)
- python - 刮掉 MP4 链接
- typescript - 有谁知道如何通过 Typescript 在 API 中使用 delete 方法?
- c++ - 如何检查 GENERIC lambda 是否可以使用某种输入参数类型调用?