1

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::getSingleton('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

Ventus
  • 2,482
  • 4
  • 35
  • 41
sushantsahay
  • 361
  • 2
  • 7
  • 15

4 Answers4

2

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

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
  • Hi Sudhir, Calling it before saving the transaction returns 0, just like my code was returning, calling it after saving the transactin return correct result. – sushantsahay Sep 04 '11 at 17:55
2

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.

Dmytro Zavalkin
  • 5,265
  • 1
  • 30
  • 34
0

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();
bitlove
  • 179
  • 1
  • 3
0

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.

Alex Gusev
  • 1,526
  • 3
  • 16
  • 35