Magento 2.1 Database – How to Get Identity ID of Last Inserted Row

databasemagento-2.1

I'm trying to insert a row in a table using following code inside controller.

protected $_objectManager;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\ObjectManagerInterface $objectManager
) 
{
    $this->_objectManager = $objectManager;
    parent::__construct($context);    
}

public function execute()
{
    $post = $this->getRequest()->getParams();
    $model = $this->_objectManager->create('<<Company Name>>\<<Module Name>>\Model\XYZ');
    $model->setData('name', $post["name"]);
    $model->setData('customer_id', $post["customer_id"]);
    $model->setData('customer_is_guest', $post["customer_is_guest"]);
    $model->setData('testCol', $post["test_col"]);

    $model->save();
}

Above code works and row gets inserted into the table, is there a way to get the id (identity id) of the row inserted above?

Best Answer

$model->getId();

if you plan to use it right after you call save.

Side note...please don't use object manager directly in your code.
Make your class look like this :

protected $modelFactory;

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \<<Company Name>>\<<Module Name>>\Model\XYZFactory $modelFactory
) 
{
    $this->modelFactory = $modelFactory;
    parent::__construct($context);    
}

public function execute()
{
    $post = $this->getRequest()->getParams();
    $model = $this->modelFactory->create();
    $model->setData('name', $post["name"]);
    $model->setData('customer_id', $post["customer_id"]);
    $model->setData('customer_is_guest', $post["customer_is_guest"]);
    $model->setData('testCol', $post["test_col"]);

    $model->save();
}
Related Topic