公用参数
$model指的是需要操作的数据库model,例如test表的
$field指的是查询的字段,例如name,id
查询单条记录
$where指的是where数组,可这么写
$where['id'] = 1;
$where['state'] = 1;
$model::find()->select($field)->where($where)->asArray()->one();
相当于以下sql
select id,name from test where id=1 and state=1;
查询多条记录,使用in
$where指的是where数组,可这么写
$where['id'] = [1,2,3];//相当于id的in
$where['state'] = 1;
$model::find()->select($field)->where($where)->asArray()->all();
相当于以下sql
select id,name from test where id in(1,2,3) and state=1;
查多条记录,使用其他运算符
$where = array('>=','id','5');
$model::find()->where($where)->asArray()->all();
相当于以下sql
select id,name from test where id >= 5;
查询多条记录,较复杂的
$model::find()->where(['and',['>=','id','5'],['=','state','1']])->asArray()->all();
相当于以下sql
select id,name from test where id >= 5 and state=1;
$where[] = 'and';
$where[] = array('<=','id','5');
$where[] = array('=','state','1');
$where_or[] = 'or';
$where_or[] = array('=','usertype','1');
$where_or[] = array('=','id','2');
$where[] = $where_or;
$model::find()->where($where)->asArray()->all();
相当于以下sql
select * from test where id <= 5 and state=1 and (usertype=1 or id=2);
$where[] = 'and';
$where[] = array('between','id',1,5);
$where[] = array('=','usertype','1');
$model::find()->where($where)->asArray()->all();
相当于以下sql
select * from test where (id between 1 and 5) and usertype=1
$where[] = 'and';
$where[] = array('like','name',['小','4']);
$where[] = array('=','usertype','1');
$model::find()->where($where)->asArray()->all();
相当于以下sql
select * from test where name like '%小%' and name like '%4%' and usertype=1
$where[] = 'and';
$where[] = array('like','name','%6%',false);
$where[] = array('=','usertype','1');
$model::find()->where($where)->asArray()->all();
相当于以下sql
select * from test where name like '%6%' and usertype=1
左链接,其他链接,换leftJoin
$field查的字段,例如u.id,u.name
$tableAs当前表别名,例如u
$model2 左链接的表model,例如test2
$tableAs2 左链接的表别名,例如login
$strOn 左链接的关联语句,例如login.userId = u.id
$where['u.id'] = [1,2];
$model::find()->alias($tableAs)
->leftJoin($model2::tableName()." $tableAs2", $strOn)
->select($field)
->where($where)
->asArray()
->all();
相当于以下sql
select u.id,u.name from test u left join test2 login on login.userId = u.id where u.id in (1,2)
统计
$model::find()->where(array())->count();
返回数字
分页
$field查的字段,例如id,name
$pageco第几条开始,例如1
$PageCount 一页显示几条,例如10
$ziduan 排序的字段,例如id
$where['state'] = 1;
$model::find()->select($field)
->where($where)
->offset($pageco)
->limit($PageCount)
->orderBy(["$ziduan"=>SORT_ASC])
->asArray()
->all();
相当于以下sql
select id,name from test where state=1 order by id ASC limit 1,10

本文详细介绍了在Yii2框架下如何使用Model进行数据库查询,包括查询单条记录、多条记录、复杂条件查询、左连接以及其他统计和分页的方法。通过示例代码展示了如何设置查询参数如$model、$field和$where,帮助开发者更好地理解和运用Yii2的数据库操作。

585

被折叠的 条评论
为什么被折叠?



