Yii:在创建期间获取控制器操作中相关表的最后插入ID

时间:2012-12-12 06:24:14

标签: php mysql yii

我有一个事务,我在TableB中插入一条新记录,并且如果TableA中没有正确的支持记录,我也将插入TableA并使用该主键作为TableB的外键入口。

enter image description here

$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之间的正确记录对齐

1 个答案:

答案 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(); 
}
相关问题