示例#1
0
 /**
  * Delete a list of models according to the primary key values.
  * @return int the number of deleted models
  */
 public function run()
 {
     $ids = Yii::$app->getRequest()->getBodyParams();
     /* @var $modelCls ActiveRecord */
     $modelCls = new $this->modelClass();
     if ($this->checkAccess) {
         call_user_func($this->checkAccess, $this->id, $modelCls);
     }
     $pks = $modelCls::primaryKey();
     $cnt = count($pks);
     if ($cnt > 1 || $cnt == 0) {
         return DbHelper::batchDelete($modelCls::tableName(), $ids);
     } else {
         $condition = [];
         $condition[$pks[0]] = $ids;
         return $modelCls::deleteAll($condition);
     }
 }
示例#2
0
 public function testBatchDeleteForNoIncrementIdModel()
 {
     /** @var User[] $inputModels */
     $inputModels = [];
     for ($i = 0; $i < 10; $i++) {
         $m = $inputModels[] = new User();
         $m->username = "******" . rand(10000, 99999);
         $m->password = $m->username;
     }
     /** @var User[] $savedReturn */
     $savedReturn = [];
     DbHelper::batchSave($inputModels, [], DbHelper::SAVE_MODE_AUTO, $savedReturn);
     /** @var User[] $savedUsers */
     $savedUsers = $savedReturn['inserted'];
     $department = new Department();
     $department->name = "Department testBatchSaveForNoIncrementIdField";
     $department->save(false);
     /** @var UserDepartmentAssignment[] $inputModels */
     $inputModels = [];
     $ids = [];
     $sql = '';
     foreach ($savedUsers as $savedUser) {
         $m = $inputModels[] = new UserDepartmentAssignment();
         $m->userId = $savedUser->id;
         $m->departmentId = $department->id;
         $ids[] = ['userId' => $savedUser->id, 'departmentId' => $department->id];
         if ($sql != '') {
             $sql = $sql . ' OR ';
         }
         $sql = $sql . "(`userId`={$savedUser->id} AND `departmentId`={$department->id})";
     }
     DbHelper::batchSave($inputModels, [], DbHelper::SAVE_MODE_AUTO);
     $return = DbHelper::batchDelete(UserDepartmentAssignment::tableName(), $ids);
     Debug::debug('Batch insert 10 UserDepartmentAssignment records. return=' . Json::encode($return));
     $this->assertEquals(10, $return);
     $sql = 'SELECT * FROM ' . UserDepartmentAssignment::tableName() . ' WHERE ' . $sql;
     $return = UserDepartmentAssignment::findBySql($sql)->count();
     $this->assertEquals(0, $return);
 }