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

Trigger deletion of old related records before saving new

I have a model - Store - with related records - StoreItem. These related records are just a mapping of a store id and an item id.

When I save a Store model, I want to delete any existing related StoreItem records, then re-add the records currently in the Store model. Is there any way to trigger that delete - or at least a custom function - when I call Store::save()?

I could use the beforeSave() event (and I will if no better solution exists), but I'd rather not delete when I don't have to. Ideally there'd be some way to mark the StoreItem records as "dirty", which would trigger a deletion before a save.

The solution I came up with is overriding __set() in my model with this code:

public function __set($name,$val){
        if($name == 'items')
            $this->itemsDirty = TRUE;

        parent::__set($name,$val);
    }

Then, in the beforeSave() function:

if($this->itemsDirty)
            $this->getItems()->delete();

I agree. There should be something to make it simpler and work in transactions.

$this->hasMany('id', 'Items', 'store_id', array(
   'alias' => 'items',
   'deleteBeforeUpdate' => true));

The workaround for many-to many relation would be something like:

$related = StoreItemsRefs::find('store_id='. $this->id);

if ($related->count() && $related->delete() == false)
   throw new Exception('Cannot delete related references to Items');

This looks dirty doesn't? Or is it just me, waiting for a cake on the table?