Yusuf
Yusuf

Reputation: 53

Yii2 model save returns true but there is no change in MySQL

Actually, If I update my model in the action of controller(in this case it is actionTest) it gets updated. Here is my code:

public function actionTest()                                                                                                    
{                                                                                                                               
    $model = ProviderOrder::find()->where(['is_used' => 0,'type' => Transaction::COD])->orderBy(['id' => SORT_ASC])->one();//const COD  = 0
    $model->is_used = 1;                                                                                                        
    $model->save();                                                                                                        
}                                                                                                                               



But in my case I defined afterSave function to my Booking model. There I call getTrackNumber function which has Transaction Class in its body.

class Booking extends ActiveRecord
{

  public function afterSave($insert, $changedAttributes)
  {
    $this->getTrackNumber($this->id);
    parent::afterSave($insert, $changedAttributes);
  }

  public static function getTrackNumber($bookingId){

    $transaction = new Transaction();
    ....
  }
 }



Inside of Transaction class there is the same code like in actionTest.

But the problem is $model->save() returns true but when I look through phpmyadmin there is no any change is_used is still 0.

But in the first case, i.e. in actionTest everything is fine. Please help me!

Upvotes: 2

Views: 427

Answers (1)

Ravi Thanki
Ravi Thanki

Reputation: 289

Can you do like below and check ?

public function actionTest()                                                                                                    
{                                                                                                                             
    $connection = \Yii::$app->db;
    $transaction = $connection->beginTransaction();  
    try{
        $model = ProviderOrder::find()->where(['is_used' => 0,'type' => Transaction::COD])->orderBy(['id' => SORT_ASC])->one();//const COD  = 0
        $model->is_used = 1;                                                                                                        
        $model->save(); 
        $transaction->commit();
    }
    catch (\Exception $e) {
       $transaction->rollback();       
    }
} 

2nd Way

$model = ProviderOrder::find()->where(['is_used' => 0,'type' => 
Transaction::COD])->orderBy(['id' => SORT_ASC])->one();//const COD  = 0
$model->is_used = 1;                                                                                                        
$model->save(false); 

Upvotes: 0

Related Questions