欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-01 17:19:46
一、新增 1、使用save() 2、使用createCommand 原生sql 3、使用createCommand insert 4、批量插入 二、删除 1、使用delete() 2、使用deleteAll()批量删除 3、使用createCommand delete() 4、使用createCom ......

 

一、新增

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();