在yii2中,我如何将多个相关记录保存到db中,成为单个保存调用和单个事务。
我有两个表:

User - id, name
UserAddress - id , user_id , city

用户表与用户地址表具有一对多关系

我想做的是:
UserAddress ua = new UserAddress();
ua.city = "fff"

User u = new User();
u.name = "test";
u.userAddress = new Array(ua);
u.save();

在用户上调用save时,也应保存user_id也设置为user.id的用户和用户地址

最佳答案

 // 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();

}

10-02 21:21