MySQL中yii2使用原生sql CURD

更多yii2使用技巧请参考:http://nai8.me/tool-sc.html

批量插入数据:

Yii::$app->db->createCommand()->batchInsert('user', ['email', 'password', 'first_name'],
[
['[email protected]', 'changeme7', 'James'],
['[email protected]', 'changeme7', 'Linda']
['[email protected]', 'changeme7']
])->execute();

更新数据:

Yii::$app->db->createCommand()->update('user', ['updated_at' => time()], 'id = 2')->execute();

删除数据:

Yii::$app->db->createCommand()->delete('user', 'id = 3')->execute();

获取所有数据(数组返回格式):

Yii::$app->db->createCommand("SELECT * FROM `user`")->queryAll();

查询一条数据:

Yii::$app->db->createCommand("SELECT * FROM `user` WHERE id = 1")->queryOne();

获取一个值:

Yii::$app->db->createCommand("SELECT count(*) AS total FROM `user` WHERE id = 1")->queryScalar();

获取某一列:

Yii::$app->db->createCommand("SELECT username FROM `user`")->queryColumn();


你可能感兴趣的:(yii笔记)