Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last inserted id in Magento customer address model

Tags:

magento

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);
       }
like image 999
tinkesh Avatar asked Mar 02 '13 15:03

tinkesh


People also ask

How to get last inserted id in magento2?

$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 .

How can I get customer address ID in Magento 2?

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 Answers

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'];
   }
like image 86
Asif hhh Avatar answered Apr 29 '23 12:04

Asif hhh