我有一个事务,我在TableB中插入一条新记录,并且如果TableA中没有正确的支持记录,我也将插入TableA并使用该主键作为TableB的外键入口。
$transaction=$connection->beginTransaction();
try
{
$tableA->IsActive = 'Y';
$tableA->save();
$model->TableAId = $tableA->TableAId; //not sure what to put here for $tableA->TableAId
$model->save();
$transaction->commit();
}
在这种情况下,我可以将Yii::app()->db->getLastInsertId();
用于$tableA->TableAId;
显然准确性非常重要,所以我需要保证TableA和TableB之间的正确记录对齐
答案 0 :(得分:2)
基本上,您的评论看起来很完美。 $ model-> TableAId = $ tableA-> TableAId; // 太棒了!! 但代码没有。以下应该是您的代码。
$transaction=$connection->beginTransaction();
try
{
$tableA = TableA::model()->findByPk("id"); OR $tableA = new TableA;
$tableA->IsActive = 'Y';
$tableA->save();
$model = new TableB;
$model->TableAId = $tableA->TableAId; //not sure what to put here for $tableA->TableAId // This is perfect!!
$model->save();
$transaction->commit();
}