我想用这些字段创建一个过滤器
如果我没有填写某些字段并提交了空值,则以下查询将不起作用。
$posts = Post::where('brand',$brand)
->where('country',$country)
->where('city',$city)
->where('car_type',$car_type)
->where('color','LIKE',$color)
->whereBetween('year',[$from_year,$to_year])
->whereBetween('milage',[$min_milage,$max_milage])
->whereBetween('price',[$min_price,$max_price])
->where('warranty',$warranty)
->where('seller_type',$seller_type)
->paginate(4);
答案 0 :(得分:3)
那是因为您告诉雄辩的是要检查数据库中的NULL,这将导致这样的查询:
WHERE brand IS NULL AND ... AND seller_type IS NULL
为避免这种情况,如果您实际上不想过滤,则一定不要对查询应用过滤器。仅像这样过滤设置值:
$posts = Post::all();
if( !is_null($brand) )
$posts = $posts->where('brand', $brand)
// ...
if( !is_null($seller_type) )
$posts = $posts->where('seller_type', $seller_type)
$posts = $posts->paginate(4);
注意:您可以获得使用toSQL
方法生成的查询:
dd( $posts->toSql() );
非常方便调试。