Yii2 save related records in single save call in single transaction

前端 未结 2 2002
醉话见心
醉话见心 2021-01-31 09:38

In yii2 how can i save multiple related records into db into single save call and single transaction. I have two tables:

User - id, name
UserAddress - id , user_         


        
2条回答
  •  星月不相逢
    2021-01-31 10:23

    Additionally to previous answer I propose variant that works without preliminarily defined relations and with explicit handling of validation errors.

    Yii::$app->db->transaction(function(){
    
        $user = new User();
        $user->name = 'Name';
    
        if( !$user->save() ){
            throw new Exception('Can\'t be saved user model. Errors: '. join(', ', $user->getFirstErrors()));
        }
    
        $userAddress = new UserAddress();
        $userAddress->city      = 'City';
        $userAddress->user_id   = $user->id;
    
        if( !$userAddress->save() ){
            throw new Exception('Can\'t be saved user address model. Errors: '. join(', ', $userAddress->getFirstErrors()));
        }
    
    });
    

    This code strictly ensures that both records will be saved. If one of model can't be saved, will be thrown exception with validation error.

提交回复
热议问题