Yii1.1 批量处理(新增、删除、修改)

$model = new UebEbayAccountNotice();
$transaction = $model->getDbConnection()->beginTransaction();

新增

//差集,需要增加的
$addUserIdArr = array_diff($newUserIdArr,$oldUserIdArr);
if (!empty($addUserIdArr)){
	$addDataArr = [];
	foreach ($addUserIdArr as $k=>$addId){
		$addDataArr[$k]['user_id'] = $addId;
		$addDataArr[$k]['notice_type'] = $data['notice_type'];
		$addDataArr[$k]['days_type'] = $data['days_type'];
		$addDataArr[$k]['is_active'] = $data['is_active'];
		$addDataArr[$k]['add_time'] = time();
	}
	$keyArr = ['user_id','notice_type','days_type','is_active','add_time'];
	$flag = $model->batchInsertAll($model->tableName(),$keyArr,$addDataArr);
}

删除

//差集,需要删除的
$delUserIdArr = array_diff($oldUserIdArr,$newUserIdArr);
if (!empty($delUserIdArr)){
	$condition = 'user_id in ('.implode(",",$delUserIdArr).') and is_active='.$isactive;
	$flag = $model->deleteAll($condition);
}

修改

$model->updateAll($attributes,$condition,$params); 
//交集,需要修改的
$updUserIdArr = array_intersect($oldUserIdArr,$newUserIdArr);
if (!empty($updUserIdArr)){
	$attributes = ['notice_type'=>$data['notice_type'],'days_type'=>$data['days_type'],'is_active'=>$data['is_active']];
	$condition = 'user_id in ('.implode(",",$updUserIdArr).') and is_active='.$isactive;
	$flag = $model->updateAll($attributes,$condition);
}

单个修改

$model = User::model()->findByPk($pk)
 $model->is_deleted = 1;
 $model->update(['is_deleted']);

#updateByPk($pk,$attributes,$condition,$params);
#$pk主键,可以是一个也可以是一个集合,$attributes是要修改的字段的集合,$condition条件,$params传入的值
$count=Admin::model()->updateByPk(1,array('username'=>'admin','password'=>'admin'));
 $count=Admin::model()->updateByPk(array(1,2),array('username'=>'admin','password'=>'admin'),'username=:name',array(':name'=>'张三'));

#自增:updateCounters($counters,$condition,$params); 
array('status'=>1)代表数据库中的admin表根据条件username='admin',查询出的所有结果status字段都自加1

事务

$transaction->commit();
$transaction->rollback();

你可能感兴趣的:(Yii1.1)