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

批量插入数据:

Yii::$app->db->createCommand()->batchInsert('user', ['email', 'password', 'first_name'],
[
['james.franklin@example.com', 'changeme7', 'James'],
['linda.marks@example.com', 'changeme7', 'Linda']
['roger.martin@example.com', '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();


Logo

更多推荐