Yii2 在单个事务中的单个保存调用中保存相关记录 [英] Yii2 save related records in single save call in single transaction
本文介绍了Yii2 在单个事务中的单个保存调用中保存相关记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 yii2 中,如何将多个相关记录保存到 db 中,以便进行单个保存调用和单个事务.我有两张桌子:
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_id , city
User 表和 UserAdress 表有一对多的关系
User table has one to many relation to UserAdress table
我想做的是:
UserAddress ua = new UserAddress();
ua.city = "fff"
User u = new User();
u.name = "test";
u.userAddress = new Array(ua);
u.save();
调用保存用户应该保存用户和用户地址,并将 user_id 设置为 user.id
calling save on user should save user and useraddress with user_id set to user.id as well
推荐答案
// 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();
}
这篇关于Yii2 在单个事务中的单个保存调用中保存相关记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文