Laravel 多条件 where 查询语句

JellyBool

JellyBool

在使用 Laravel 开发应用的时候,还是会经常遇到多条件的查询语句,比如一个网站的商品筛选页面就有可能是这样子:

http://jd.com/products?color=black&size=xl&orderBy=price&sort=desc

这种方式的筛选其实我们就会使用多条件的 where 语句来做,比如我们通常会看到类似下面的代码:

$query = Product::newInstance();
 
if ($request->color) {
    $query->whereColor($request->color);
}
 
if ($request->size) {
    $query->whereSize($request->size);
}
 
if ($request->orderBy && $request->sort) {
    $query->orderby($request->orderBy, $request->sort);
}
 
$products = $query->get();

那如果说,你需要一个默认的排序结果的话,可以这样:

...其他代码
if ($request->orderBy && $request->sort) {
    $query->orderby($request->orderBy, $request->sort);
} else {
    $query->orderby('price', 'desc');
}
...其他代码

然而如果说你使用条件性的 where 查询的话,可以这样:

$products = Product::when($request->color, function ($query) use ($request) {
    return $query->whereColor($request->color);
})
->when($request->size, function ($query) use ($request) {
   return $query->whereSize($request->size);
})
->when($request->orderBy && $request->sort, function ($query) use ($request) {
   return $query->orderBy($request->orderBy, $request->sort);
})
->get();

需要默认排序的情况则是这样:

...其他代码
->when($request->orderBy && $request->sort, function ($query) use ($request) {
   return $query->orderBy($request->orderBy, $request->sort);
}, function ($query) {
   return $query->latest('price');
})
...其他代码

到这里就可以解决 Laravel 的多条件查询了!

双十一关注公众号 codecasts 即送 100 元订阅优惠劵的活动还有效!CODECASTS 支持 ETC BTC等电子购买订阅会员啦!
图片描述

本文由 JellyBool 创作, 转载和引用遵循 署名-非商业性使用 2.5 中国大陆 进行许可。

共有 6 条评论

H_Project

受教了!之前都是Model->where(function(query)use(query) use (req){
if(***)
})

nicoke

请问whereColor是什么方法?

尼好再见 回复 nicoke

应该是自定义的方法

jasester 回复 nicoke

缩写,color是字段,比如表中有type字段,可以写成whereType ,或is_del可以写成whereIsDel

jasester
$query = Product::newInstance();

楼主这个是什么意思啊?

JellyBool 回复 jasester

你直接 new Product 可以么?

jasester 回复 JellyBool
$product = (new Product);
$query = $product->whereColor();
这样吗?
我是这样写的对吗?
$query = Product::select('*');
$query = $product->whereColor();
xw716825

jelly,Product::newInstance()不对呢,用实例调用这个方法好像也不对呢

JellyBool 回复 xw716825

你直接 new Product 可以么?试试》

smile2017

如果是属性名 属性值 的那种多条件查询,怎么实现?

如表A:
id, product_id, product_attribute_id, product_attribute_value

当多条件的时候 如何快速查询到product_id

JellyBool 回复 smile2017

id, product_id, product_attribute_id, product_attribute_value

这是一条记录还是字段?

smile2017 回复 JellyBool

记录,但是商品和和商品属性是多对多的关系

yb198900724 回复 smile2017

在关联的查询上写限制条件就好了

假如_丶

补充一下,刚踩的坑,where语句有前提条件时,比如某值为1的时候才执行where子句,否则不执行。对!没有错!你的值为0的时候不执行的!

    ```
    // 解决方案
    ->when($status, function ($query) use ($status) {
            return $query->where('status', 1);
        }, function ($query) use ($status){
            return $query->where('status', 0);
        })
    ```