php - Yii:在创建期间获取 Controller 操作中相关表的最后插入 ID

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

最佳答案

基本上,您的评论看起来很完美。 $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/

相关文章:

php - 打印出 SQL 单个查询 (Yii 1.x)

xml - Magento XML $this->getChildHtml() 有必要吗?

mysql - 具有动态字段的查询表

php - 如何分解数组并插入到 MySQL 中

Yii CAPTCHA 网址已损坏

php - 仅为两个 Controller 分配不同的域

openid - 如何使用 Yii 和 OpenID 登录用户

php - 如何将 PhoneGap 应用程序连接到我的托管网站中的数据库?

php - redis 连接成功后数据未投递到 redis

php - 第 15 行的 fatal error : Allowed memory size of 67108864 bytes exhausted (tried to allocate 35 bytes) in/home/content/08/10674308/html/Arraytest. php