我有一个事务,我正在向 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 之间的正确记录对齐
最佳答案
基本上,您的评论看起来很完美。 $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();
}
关于php - Yii:在创建期间获取 Controller 操作中相关表的最后插入 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13834000/