duanji4870 2015-02-25 13:58
浏览 38
已采纳

在Yii 1.x中运行事务查询

I am trying to run a transactional query using Yii 1.x - this should basically rollback all the queries if there is a problem, can people confirm this is the correct way to run transactions using Yii 1?

// data comes from a csv
 $transaction = Yii::app()->db->beginTransaction();
    try
    {

        if (($handle = fopen($path, "r")) !== false) {
            while (($data = fgetcsv($handle)) !== FALSE) {
                if ($currentRow == 1) {
                    $header = $this->import_fields(array_map('strtolower', $data));
                    $currentRow++;
                    continue;
                } else {
                    $data = array_combine($header, $data);
                    $csv_import_model = null;

                    if (!empty($data['username'])) {
                        $csv_import_model = StudentImportForm::model()->findByAttributes(array(
                            'username' => $data['username'],
                            'organisation_id' => user()->data->organisation->getViewOrgId()
                        ));
                    }

                    if (is_null($csv_import_model)) {
                        $csv_import_model = new StudentImportForm();
                        $isNew = true;
                    } else {
                        $isNew = false;
                    }

                    $csv_import_model->scenario = 'import';
                    $csv_import_model->setAttributes($data);
                    $csv_import_model->unsetAttributes(array('password'));

                    if ($csv_import_model->validate()) {

                        if (in_array($csv_import_model->username, $processedUsername)) {
                            $csv_import_model->addError('username', sprintf('Duplicate username (%1$s) found in csv file. which may already exists on row number %2$s.', $csv_import_model->username, (array_search($csv_import_model->username, $processedUsername) + 1)));
                        } else {

                            if ($csv_import_model->save()) {

                                if ($isNew) {
                                    $this->csv_results['inserted'] = $this->csv_results['inserted']+1;
                                } else {
                                    $this->csv_results['updated'] = $this->csv_results['updated']+1;
                                }

                            } else {
                                $this->csv_results['error'][$currentRow] = $csv_import_model->getErrors();
                            }
                        }
                    } else {
                        $csv_import_model->csv_index = $currentRow;
                        $this->csv_results['error'][$currentRow] = $csv_import_model->getErrors();
                    }

                    $processedUsername[] = $csv_import_model->username;

                    $currentRow++;
                    Yii::getLogger()->flush(false);
                }
            }
            fclose($handle);
        }

        $transaction->commit();
    }
    catch(Exception $e)
    {
        $transaction->rollback();
    }
  • 写回答

1条回答 默认 最新

  • duanbi6522 2015-02-25 14:09
    关注

    $model->save() doesn't throw an exception in case it fails. It returns true or false. In order to rollback the entire block, you must manually throw an exception if save() returns false. Try something like this:

    $errors = null;
    try {
        if ($csv_import_model->save()) {
            // continue with whatever logic you have
            $transaction->commit();
        }else{
            $errors = 'Error when saving';
            throw new Exception('Could not save model');
        }
    }catch(Exception $e){
       //Do some logging here
       $transaction->rollback();
       if($errors != null){
           Yii::app()->user->setFlash('error', $errors);
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办