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 to unbind/unlink relations before update? Problem with update.

Hi, If i have two models, for example Users and Orders and i run this code:

$order = Orders::findFirstById(1);

echo $order->user->name;

$order->update();

Phalcon is firing beforeUpdate() in Users model. How to prevent this? How to unbind/unlink relations before update? The only thing I can do now is to reload the record before update.

$order = Orders::findFirstById(1);

echo $order->user->name;

$order = Orders::findFirstById(1);

$order->update();

This will not fire beforeUpdate() in Users model. I tried to add 'foreignKey' => array('action' => \Phalcon\Mvc\Model\Relation::NO_ACTION) in Orders model but it doesnt work.

Relation in Orders:

$this->belongsTo('user_id', '\Model\Users\Users', 'id', array( 'alias' => 'user', 'reusable' => true, 'foreignKey' => array('action' => \Phalcon\Mvc\Model\Relation::NO_ACTION)
));

The problem is that i'm changing user modification time in beforeUpdate() in Users model, so when i update Orders without changing anything in Users (only getting name for example) Phalcon is updating modification time in Users.



1.0k

I'm using 2.0.9 verison. I think that on 1.3 everything was ok.

edited Feb '16

I would tend to think this is a bug. The user shouldn't update because it wasn't changed. The only thing I can think of is to set a flag in user like skipBeforeUpdate - then in your User::beforeUpdate() method, you only do stuff if skipBeforeUpdate is false. This method will work, but you'll have to set that flag everywhere you save an order and don't want the user to update.

I assume your example was simplified for the purpose of posting to this forum?



1.0k
edited Feb '16

Yes, example was simlified. I have many palces in code with similar situation, so it looks i should rewrite everything. In Phalcon 1.3 everthing was ok. Maybe i should check in beforeUpdate() if any records was changed and skip if no.

edited Feb '16

Or try to change the relation... amm, like- hasOne ?



1.0k
edited Feb '16

hasOne doesnt help.

In Orders i have:

$this->belongsTo('user_id', '\Model\Users\Users', 'id', array( 'alias' => 'user', 'reusable' => true ));

In Users: $this->hasMany('id', '\Model\Orders\Orders', 'user_id', array( 'alias' => 'orders', 'reusable' => true ));



1.0k
edited Feb '16

I added this in Users model.

public function beforeUpdate() {
$changedFields = $this->getChangedFields(); if(empty($changedFields)) return; $this->setModified(new RawValue('NOW()')); }