Hi all,
I am new to Yii, Just started to use the framework a week back and have to say its really way ahead of other frameworks I have used. Hats off to all the Developers and Contributors.
I am stuck with a problem, I want to insert new records in two of my tables using Active Record and Transaction. such that either both of the tables are inserted with new record or none, while I use the transaction I am not able to do this correctly.
Here is the first way
$model = User::model();
$model->uit = $this->_generateUit($model->name, $model->email);
$model->created_at = date('Y-m-d H:i:s');
$model->updated_at = date('Y-m-d H:i:s');
$token = Token::model();
$token->token=$token->generateToken($model->name);
$token->uit = $model->uit;
$token->created_at=date('Y-m-d H:i:s');
$transaction = $token->dbConnection->beginTransaction(); // Transaction begin
try{
$token->save(); // saving token
$model->save(); // saving user
throw new Exception($error); // <---- Added to check on error condition.( test only)
$transaction->commit(); // committing
$this->redirect(array('view','id'=>$model->id)); // Redirecting on user creation
}
catch (Exception $e){
$transaction->rollBack();
}
The following code actually saves the user to the DB, this should be as no transaction is applied on $model (User AR)
The second way
$model = User::model();
$model->uit = $this->_generateUit($model->name, $model->email);
$model->created_at = date('Y-m-d H:i:s');
$model->updated_at = date('Y-m-d H:i:s');
$token = Token::model();
$token->token=$token->generateToken($model->name);
$token->uit = $model->uit;
$token->created_at=date('Y-m-d H:i:s');
$tokentransaction = $token->dbConnection->beginTransaction(); // Transaction for token begin
$modeltransaction = $model->dbConnection->beginTransaction(); // Transaction for model begin
try{
$token->save(); // saving token
$model->save(); // saving user
$modeltransaction->commit(); // committing model
$tokentransaction->commit(); // committing token
$this->redirect(array('view','id'=>$model->id)); // Redirecting on user creation
}
catch (Exception $e){
$modeltransaction->rollBack();
$modeltransaction->rollBack();
}
In this case it gives out an error for a transaction being already active.
I do not want to use DAO, is there some solution to this problem using AR.
Thanks