yii2中,经常会使用很多条件进行组合判断查询数据,和laravel 中不同,laravel 闭包函数查询
$data = Student::where(function ($query) use ($request) {
$id = $request->input(‘id‘);
$name = $request->input(‘name‘);
$query->where(‘id‘, ‘like‘, ‘%‘ . $id . ‘%‘)->where(‘sname‘, ‘like‘, ‘%‘ . $name . ‘%‘);
})->get()->toArray();
那么在yii2中多条件没有闭包函数,我们需要把条件通过判断封装到where条件里面,
字符串和哈希格式很好理解,就是直接把值和变量绑定 起来,这种更加简单。我们来看看操作符格式,因为操作符格式可以组成相对复杂的查询语句。下面我们查询一个商店订单的给的例子
$where = ['and'];
if(!empty($data['order_no'])) {
array_push($where,['like','order_no','%'.trim($data['order_no']).'%', false]);
}
if(!empty($data['shop_ids']) && is_array($data['shop_ids'])) {
$where[] = ['in','shop_id',$data['shop_ids']];
}
$query = Shop::find()
->where($where)
->select(['shop.name','order.money'])
->leftJoin('order','order.id=shop.order_id');
if($data['group'] !=2 ){
$query->orderBy('(CASE
WHEN status = 1 THEN 2
WHEN status = 2 THEN 1
WHEN status = 3 THEN 0
WHEN status = 4 THEN 0
WHEN status = 5 THEN 0
WHEN status = 6 THEN 0
END) desc')
->addOrderBy('shop.pay_time', 'desc');
}
$query = $query->addOrderBy('shop.create_time', 'desc');
$count = $query->count();
$pagination = new Pagination(['count' => $count, 'pageSize' => $pageSize, 'page' => $page - 1]);
$offset = ($page - 1) * $pagination->limit;
$list = $query->offset($offset)->limit($pagination->limit)->all();
这样一来,就把闭包函数处理成where条件的形式。