We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How Do You STOP Phalcon Models from Auto Saving Related Records?

We are using Phalcon to handle our API and a sa result we often like to return back portions of related records. One thing I'm finding that might be bad design on my end is when I'm working with an object to return and I have to do a quick update on it - it's cascading that update to related records, which I don't want to happen..

Simple example: $customer = new \Models\FindFirst($id); $customer->referred_by; // touch it to return it $customer->last_login = time(); $customer->update(); return $customer;

Above code will try to do an update on the referred by object too. This is causing some serious issues in some palces of our code. There must be a way to programmatically turn this off. How can I do that?

Dan

edited Mar '16

There is no setting or option which will disable this functionality, but you can override model methods _preSaveRelatedRecords and _postSaveRelatedRecords

/*
 * Saves related records that must be stored prior to save the master record
 *
 * @param \Phalcon\Db\AdapterInterface connection
 * @param \Phalcon\Mvc\ModelInterface[] related
 * @return boolean
 */
protected function _preSaveRelatedRecords(\Phalcond\Db\AdapterInterface $connection, $related)
{
    ...
}

/*
 * Save the related records assigned in the has-one/has-many relations
 *
 * @param  Phalcon\Db\AdapterInterface connection
 * @param  Phalcon\Mvc\ModelInterface[] related
 * @return boolean
 */
protected function _postSaveRelatedRecords(\Phalcond\Db\AdapterInterface $connection, $related)
{
    ...
}

https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L2499 https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L2595



7.1k

This is an issue in general because the models are always added to the _related array when retrieved. Locally we fixed this issue by overriding __get and unsetting the _related entry for that alias after calling parent::__get.