Updating and delete Related Models (Relational tables) in Yii

后端 未结 1 1047
一生所求
一生所求 2021-01-27 10:08

UPDATED
I have two related models i.e. Candidate and Qualifications. They have one to one relationship between them. I am using CActiveForm and want to pe

相关标签:
1条回答
  • 2021-01-27 11:01

    UPDATING

    It seems, you only have a one-to-one relationship so if that is the case you only have to link $q to the specific qualification:

    public function actionUpdate()
       {
        //load model
        $q=&$model->qualifications[0];
        if (isset($_POST['Candidate'], $_POST['Qualification'])) {
            $model->attributes=$_POST['Candidate'];
            $q->attributes=$_POST['Qualification'];
    
            $error = false;
            $transaction = Yii::app()->db->beginTransaction();
            try {
                if (!$model->save()) {
                    throw new CException(CHtml::errorSummary($model));
                }
                if (!$q->save()) {
                    throw new CException(CHtml::errorSummary($q));
                    echo $error;
                }
                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();
                $error = $e->getMessage();
            }
    
            if (!$error) {
                $this->redirect(array('view','id'=>$model->id));
            }
        }
    

    With some tweaks i.e a loop and tabular data input the above code can work for one-to-many.

    DELETING

    For deletion edit Candidate::beforeDelete() to delete all qualifications linked to it as follows:

    public function beforeDelete(){
        foreach($this->qualifications as $q)
            $q->delete();
        return parent::beforeDelete();
    }
    

    You should wrap the call to Candidate::delete() in a transaction.

    0 讨论(0)
提交回复
热议问题