0

I have created a model and a repository to save the model, the only functions I can find in the model->getResource() are save, load and delete. The save function always uses an UPDATE statement, so how can I save a new instance of my model to the database?

I am a bit confused because while searching for a solution I could only find people who have the opposite problem, their save function uses an INSERT INTO statement instead of UPDATE.

0

Magento save and update inside save method in resource model class. Goto here Method looks like:


public function save(\Magento\Framework\Model\AbstractModel $object)
{
    if ($object->isDeleted()) {
        return $this->delete($object);
    }

    $this->beginTransaction();

    try {
        if (!$this->isModified($object)) {
            $this->processNotModifiedSave($object);
            $this->commit();
            $object->setHasDataChanges(false);
            return $this;
        }
        $object->validateBeforeSave();
        $object->beforeSave();
        if ($object->isSaveAllowed()) {
            $this->_serializeFields($object);
            $this->_beforeSave($object);
            $this->_checkUnique($object);
            $this->objectRelationProcessor->validateDataIntegrity($this->getMainTable(), $object->getData());
            if ($this->isObjectNotNew($object)) {
                $this->updateObject($object);
            } else {
                $this->saveNewObject($object);
            }
            $this->unserializeFields($object);
            $this->processAfterSaves($object);
        }
        $this->addCommitCallback([$object, 'afterCommitCallback'])->commit();
        $object->setHasDataChanges(false);
    } catch (\Exception $e) {
        $this->rollBack();
        $object->setHasDataChanges(true);
        throw $e;
    }
    return $this;
}

Actually following line perform update or insert


if ($this->isObjectNotNew($object)) {
    $this->updateObject($object);
} else {
    $this->saveNewObject($object);
}
  • Thank you, apparently isObjectNotNew() checks if the object has an ID, and my model does not use an identity column so the objects always had an ID when I set their data – Kaascroissant Sep 22 '17 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.