本文实例讲述了Yii2.0框架模型添加/修改/删除数据操作。分享给大家供大家参考,具体如下:
添加数据
代码语言:javascript复制$user = new User();
$user- name = 'zhang';
$user- age = 28;
$data = $user- save();//添加数据
$data = $user- insert();//添加数据
$id = $user- attributes['id'];//获取当前添加数据后的自增id
修改数据
代码语言:javascript复制$user = $User::findOne(1);
$user- name = 'zhang';
$data = $user- update();//修改
$data = $user- save();//修改
//修改单个字段
$data = Uesr::updateAllCounters(['name' = 'li'],['id' = 1]);//参数1为要修改的字段,参数2为修改条件
删除数据
代码语言:javascript复制//删除数据
$user = User::find()- where(['id' = 2])- one();//获取id为2的数据
$data = $user- delete();//删除数据
$uer = User::find()- where(['id' = 2])- all();//获取id为2的数据
$data = $user[0]- delete();//删除数据
//删除所有数据
$user = User::deleteAll();
$user = User::deleteAll('id=2');//删除id为2的数据
//多个条件删除
$data = User::deleteAll('id :id AND num<:num',[':id' = 2,':num' = 100]);