YII2中的yii\db\Query给我们提供了非常丰富的方法,方便我们构建复杂的SQL语句。
Query()与createCommand最大区别在于,后者直接使用我们写好的SQL语句,前者通过参数和数据库类型生成不同SQL,迁移性更好。
<?php namespace app\controllers; use YII;
use yii\db\Query;
use yii\web\Controller; class TestController extends Controller
{
public function actionTest()
{
//YII2的Query的使用
//Query与createCommand的区别是createCommand是直接写一个SQL来执行。
//Query是根据参数和数据库类型生成不同的SQL,提升数据库可迁移性。 //通过all查询多条记录
//我这里用tb_user表来进行演示
$data1 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->all(); //指定where条件查询
$data2 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where('id=:id', [':id' => '2'])
->all(); //通过one查询单条记录
$data3 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where('id=3')
->one(); //判断记录是否存在
$exists = (new Query())->from('{{%user}}')
->where('name="aaa"')
->exists(); if ($exists) {
echo 'name=aaa 存在';
} //定义字段别名
//注意真实的字段名写后面,别名写前面
$data4 = (new Query())->select(['ids' => 'id', 'names' => 'name'])
->from('{{%user}}')
->where('1=1')
->all(); //通过orderby排序,和limit限制条数
$data5 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where('1=1')
->orderBy('id desc')
->limit(3)
->all(); //多个and条件
//参数是数组,一个key对应一个value,默认以and拼接
$data6 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['id' => 3, 'name' => 'aaa'])
->one(); //in条件
$data7 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['id' => [4, 5, 6]])
->all(); //或者如下方式
$data7_2 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['in', 'id', [4, 5, 6]])
->all(); //count统计
$count = (new Query())->from('{{%user}}')->count();
echo '总记录数: ', $count; //大于,大于等于,小于,小于等于where条件
$data8 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['>=', 'id', 5])
->all(); $data9 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['<=', 'id', 3])
->all(); //like查询
$data10 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['like', 'name', 'dd'])
->all(); //between筛选和group by分组
//查找出age在18到24之间的,并按sex分组
$data11 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['between', 'age', 18, 24])
->groupBy('sex')
->all(); //having筛选
//按sex分组,然后统计人数大于3的
$data12 = (new Query())->select(['sex', 'cnt' => 'count(*)'])
->from('{{%user}}')
->groupBy('sex')
->having('cnt > 3')
->all(); //or逻辑条件
//查找姓名为aaa或bbb的用户
//之前where数组是以key=>value方式传递的,如果要表达复杂逻辑关系,
//数组第一个元素必须声明是什么逻辑,and还是or
//第二个元素表示逻辑左边
//第三个元素表示逻辑右边
$data13 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['or', ['name' => 'aaa'], ['name' => 'bbb']])
->all(); //复杂的where条件
//我这里只是作为演示
//SELECT `id`, `name` FROM `tb_user` WHERE ((`name`='aaa') OR (`name`='bbb')) OR ((`name`='ccc') OR (`name`='ddd'))
$data14 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where([
'or',
[
'or',
['name' => 'aaa'],
['name' => 'bbb'],
],
[
'or',
['name' => 'ccc'],
['name' => 'ddd'],
],
])
->all(); //and和or嵌套where条件
//SELECT `id`, `name` FROM `tb_user` WHERE (`sex`=1) AND ((`name` LIKE '%aa%') OR (`name` LIKE '%bb%'))
$data15 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where([
'and',
['sex' => 1],
[
'or',
['like', 'name', 'aa'],
['like', 'name', 'bb'],
],
])
->all(); //有些时候我们需要根据用户传递过来的参数追加where条件
//追加and条件
$query = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where('sex=1');
//追加age大于18的条件
$query->andWhere(['>', 'age', 18]);
echo $query->createCommand()->getRawSql(); //追加or条件
$query2 = (new Query())->select(['id', 'name'])
->from('{{%user}}')
->where(['like', 'name', 'aa']);
//追加name相似bb的条件
$query2->orWhere(['like', 'name', 'bb']);
echo $query2->createCommand()->getRawSql(); //表别名和连接查询
//SELECT `u`.`id`, `u`.`name`, `aa`.`item_name` FROM `tb_user` `u` LEFT JOIN `tb_auth_assignment` `aa` ON aa.user_id = u.id
$data16 = (new Query())->select(['u.id', 'u.name', 'aa.item_name'])
->from(['u' => '{{%user}}'])
->leftJoin(['aa' => '{{%auth_assignment}}'], 'aa.user_id = u.id')
->all();
}
}