I am saving the customer address in the customer_address_entity
table. Everything is ok but I want to get the last generated entity_id
. Can somebody help me?
I have the following code;
$customAddress = Mage::getModel('customer/address');
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('0')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
} catch (Exception $ex) {
Mage::log("\n Address save Error:: \n" . $ex->getMessage(), null, $this->log_entry_file);
}
$freeevent = Mage::getModel('freeevent/freeevent'); $freeevent->setData('firstname', $firstname); $freeevent->setData('lastname', $lastname); $freeevent->save(); $getLastId = $freeevent->getId(); use this code to get the last inserted id in magento .
You can get the customer address data by Address id using AddressRepositoryInterface interface. Magento\Customer\Api\AddressRepositoryInterface contains the getById($addressId) function with pass first argument as address id to fetch specific customer address data.
1 - when using a model, this returns the recently added/saved item id by $model object
$model->getId()
2 - But when using a custom query , then use following to get last inserted id
$connection = Mage::getSingleton(’core/resource’)->getConnection(’core_write’);
$sql = "INSERT INTO <table> SET field1 = ?, field2 = ?, ...";
$connection->query($sql, array($field1_value, $field2_value, ...));
$lastInsertId = $connection->lastInsertId();
echo $lastInsertId;
3 - From a specific table, get the last inserted id by defining your own function
function getLastInsertId($tableName, $primaryKey)
{
//SELECT MAX(id) FROM table
$db = Mage::getModel('core/resource')->getConnection('core_read');
$result = $db->raw_fetchRow("SELECT MAX(`{$primaryKey}`) as LastID FROM `{$tableName}`");
return $result['LastID'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With