开发者

Magento last insert id in middle of transaction

开发者 https://www.devze.com 2023-04-02 20:04 出处:网络
I am using transactions in Magento. I need to use primeryKey of first insert query to all my subsequent queries.

I am using transactions in Magento. I need to use primeryKey of first insert query to all my subsequent queries.


    $model1->setfield1()
           ->setField2();
    $transaction->addObject($model1);
    $connection    = Mage::ge开发者_Go百科tSingleton('core/resource')->getConnection('core_read');
    $lastInsertId  = $connection->fetchOne('SELECT last_insert_id()'); // return 0
    $model2->setfield3($lastInsertId )
    $model3->setfield4($lastInsertId )
    $transaction->addObject($model2);
    $transaction->addObject($model3);

    $transaction-Save();
    $lastInsertId2  = $connection->fetchOne('SELECT last_insert_id()'); // returns correct result

how to get last inserted id before saving the transaction


I guess PDO (which magento uses) can't get last_inserted_id while transaction isn't commited yet. I guess you should either try plain sql like there or try use nested transactions.


Tyy this: $lastInsertId = $connection->lastInsertId();


Not sure about the case with transactions, but I usually do it like this:

$data = $this->getRequest()->getPost();
$list = Mage::getModel('myextension/list')->setData($data);
$list->setUserId($userId)
    ->setCreatedTime(now());

try
{
 $list->save();
}
catch(Exception $e)
{
 Mage::getSingleton('core/session')->addError($e->getMessage());
 return $this->_redirect('*/*/');
}

$last_insert_id = $list->getId();


Magento transaction does not change data in the DB until you call save() method:

$transaction->addObject($model1);
...
$transaction->save();

addObject() just adds new object to the transaction's registry (\Mage_Core_Model_Resource_Transaction::$_objects). $model1->save() method will be called on $transaction->save(). No INSERT operation is performed before $transaction->save() call.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号