Magento2 – Use of getId() & setId() in Mage_Core_Model_Abstract

modelsave

I want to understand functions of mage_core_model_abstract.

For this I'm using Mage::log() function in different places.

and I'm using custom module with model.

I'm thinking getId() & setId() functions will call If i save new record in db or update exist record of model in the process of save() function.

But in magento log i'm not getting any values.

For example my custom module with 3 fields(entity_id(primary key & auto increment),field1,field2).
and I have 3 records like this

1 apple yellow

2 flower green

3 fruit red

If i edit first record & save I should get $object->getId() value "1" In

Mage_Core_Model_Resource_Db_Abstract::save(Mage_Core_Model_Abstract
$object).

If I add new record magento should pass "4" value to $object->setId($id).

please look at line $object->setId($this->_getWriteAdapter()->lastInsertId($this->getMainTable()));
Am i correct?

update:
following updated successfully.Normally everyone using load($id) function.

 $_book = Mage::getModel('namespace_module/mydata');
$_book->setId(7)->setField1('85')->setField2("jkl")->save();

Best Answer

Magento doesn't define the next entity_id value as it auto increments, MySQL will set this when you save a new object - thus you won't see a call to setId(). You also won't see a call to getId() when loading the object as it's done in the format:

$model = Mage::getModel('module/model')->load($id);

so you need to know the id of the model before you load it - either that or you filter the collection by other parameters to select the correct model.

If you instantiate a model with just:

$model = Mage::getModel('module/model');

and then save() it you will enter a new row into the table of interest and on save and the entity_id of this new row will be populated into the model as it's id as it didn't exist before. If you instantiate a model with instead:

$model = Mage::getModel('module/model')->load($id);

this will pull an existing row from the database table according to the id you specify, in this case when you save, as the id is already in the object, the relevant row in the relevant table is instead updated. So the key here is the existence of an id in the instantiated model object, no id = new entry is saved vs id exists = existing entry is updated.

The only time you are going to see a call to the getId() or setId() methods of an object if is some code dealing with the object after it's loaded calls it, you won't see it during the standard load or save process.

And by the way, you are calling getId() and not just getId?

Related Topic