Yii2 save related records in single save call in single transaction

前端 未结 2 2004
醉话见心
醉话见心 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:21

     // You need create hasMany relation 'userAddress' (look guide relations)
    
    $transaction = Yii::$app->db->beginTransaction();
    
    try {
    
        $user = new User();
        $user->name = 'Name';
        $user->save();
    
        $ua = new UserAddress();
        $ua->city = 'City';
    
        $user->link('userAddress', $ua); // <-- it creates new record in UserAddress table with ua.user_id = user.id
    
        $transaction->commit();
    
    } catch (Exception $e) {
    
        $transaction->rollBack();
    
    }
    

提交回复
热议问题