Yii2数据库操作

1、常用查询

// WHERE admin_id >= 10 LIMIT 0,10
 User::find()->select('*')->where(['>=', 'admin_id', 10])->offset(0)->limit(10)->all()
// SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`   
 $subQuery = (new Query())->select('COUNT(*)')->from('user');    
 $query = (new Query())->select(['id', 'count' => $subQuery])->from('post');
// SELECT DISTINCT `user_id` ... 
 User::find()->select('user_id')->distinct();

2、更新操作

//update();
//runValidation boolen 是否通过validate()校验字段 默认为true 
//attributeNames array 需要更新的字段 
$model->update($runValidation , $attributeNames);  

//updateAll();
//update customer set status = 1 where status = 2
Customer::updateAll(['status' => 1], 'status = 2'); 

//update customer set status = 1 where status = 2 and uid = 1;
Customer::updateAll(['status' => 1], ['status'=> '2','uid'=>'1']);

//updateAllCounters()在数据库值的基础上进行操作

Customer::updateAllCounters(['age' => 1]); //增加所有年龄字段加1


继续阅读Yii2数据库操作