如何在Magento客户地址模型中获取最后插入的ID

tin*_*esh 6 magento

我正在保存customer_address_entity表中的客户地址.一切都好,但我想得到最后一次生成entity_id.有人能帮助我吗?

我有以下代码;

        $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);
       }
Run Code Online (Sandbox Code Playgroud)

Asi*_*hhh 12

1 - 使用模型时,它返回$ model对象最近添加/保存的项ID

    $model->getId()
Run Code Online (Sandbox Code Playgroud)

2 - 但是在使用自定义查询时,请使用以下内容来获取最后插入的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; 
Run Code Online (Sandbox Code Playgroud)

3 - 从特定表中,通过定义自己的函数获取最后插入的id

   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'];
   }
Run Code Online (Sandbox Code Playgroud)


Ren*_*art 10

保存使用后获取id getId()

...
try {
       $customAddress->save();
       echo $customAddress->getId(); 
 }
....
Run Code Online (Sandbox Code Playgroud)


use*_*094 5

If you use magento save method than try this to get the last inssert id.

$order->save();
Afetr save method use getId method to get the last insert id in magento 
echo $order->getId(); 


//For custom connection use 
$db_write = Mage::getSingleton('core/resource')->getConnection('core_write');
$sqlQuery = "SELECT * FROM TABLE_NAME ";
$db_write ->query($sqlQuery);
echo $lastInsertId  = $db_write ->fetchOne('SELECT last_insert_id()'); 
                              OR

echo $db_write ->lastInsertId(); // you may also try this.

For more Info 
Run Code Online (Sandbox Code Playgroud)

点击这里