Yii2 中常用的增删改查操作总结

2019-07-23 08:41:28来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

 

一、新增

1、使用save()

$model = new User();
$model->name = 'test';
$model->phone = '13000000000';
$model->email = '123456@qq.com';
$model->save();

2、使用createCommand 原生sql

$sql = "insert into user (name, phone, email) values ('test', '13000000000', '123456@qq.com')";
Yii::$app->db->createCommand($sql)->execute();

3、使用createCommand insert

Yii::$app->db->createCommand()->insert('user', [
    'name' => 'test',
    'phone' => '13000000000',
    'email' => '123456@qq.com'
])->execute();

4、批量插入

Yii::$app->db->createCommand()->batchInsert('user', ['name', 'phone', 'email'], [
    ['test1', '13000000000', '123456@qq.com'],
    ['test2', '13000000001', '234567@qq.com']
])->execute();

 

二、删除

1、使用delete()

$user = User::find()->where(['name' => 'test'])->one();
$user->delete();

2、使用deleteAll()批量删除

User::deleteAll(['name' => 'test']);

3、使用createCommand delete()

Yii::$app->db->createCommand()->delete('user', ['name' => 'test'])->execute();

4、使用createCommand 原生sql

$sql = "delete from user where name = 'test'";
Yii::$app->db->createCommand($sql)->execute();

 

三、更新

1、使用update()

$user = User::find()->where(['name' => 'test'])->one();
$user->phone = '13100000000';
$user->update();  // 或者 $user->save();

2、使用updateAll()

User::updateAll(['phone' => '13100000000'], ['name' => 'test']);

3、使用createCommand update()

Yii::$app->db->createCommand()->update('user', ['phone' => '13100000000'], ['name' => 'test'])->execute();

4、使用createCommand 原生sql

$sql = "update user set phone = '13100000000' where name = 'test'";
Yii::$app->db->createCommand($sql)->execute();

 

四、查询

1、使用model

// 查询一条记录
User::find()->select(['name', 'phone', 'email'])->where(['phone' => '13000000000'])->andWhere(['like', 'name', 'test'])->one();
// 查询一条记录数组返回
User::find()->where(['name' => 'test'])->asArray()->one();
// 查询所有记录
User::find()->where(['name' => 'test'])->all();
// 查询所有记录数组返回
User::find()->where(['name' => 'test'])->asArray()->all();

2、使用createCommand

// 查询一条记录
Yii::$app->db->createCommand("select * from user where name = :name and phone = :phone")->bindValues([':name' => 'test', ':phone' => '13000000000'])->queryOne();
// 查询所有记录
Yii::$app->db->createCommand("select * from user where name = :name and phone = :phone")->bindValues([':name' => 'test', ':phone' => '13000000000'])->queryAll();

3、使用yii\db\Query()

(new \yii\db\Query())->from('user')->where(['name' => 'test'])->all();

4、子查询

$subQuery = (new \yii\db\Query())->select(['id'])->from('user')->where(['like', 'name', 'test'])->all();
(new \yii\db\Query())->from('user')->where(['in', 'id', $subQuery])->all();

 


原文链接:https://www.cnblogs.com/woods1815/p/11145063.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:php的微信公众平台开发接口类

下一篇:【php socket通讯】php实现http服务