Search code examples
ormfuelphp

Fuelphp Save delete relation, Observer calls before_update but not before_delete


I have an Observer on a has_many relationship like this:

Post has_many Comments

and Comments has the following Observer activated:

class Observer_Comments
{
    public function before_delete($model)
    {
        Log::info("Deleted a comment");
    }
    public function before_update($model)
    {
        Log::info("Updated a comment");
    }
}

When I update my Post model like this:

$post = Post::find(1)->related('comments);
unset($post->comments[1]);
$post->save();

My log does not show any activity. The Comment is deleted, and the Post is updated correctly, including running any of its observers.

When I delete a comment explicitly:

$comment = Comment::find(1);
$comment->delete();

then the log shows what I expect:

INFO --> Deleted a Comment

Is there a cascade setting I have to use?


UPDATE

I see this code inside of Model::save():

1127    if (method_exists($rel, 'delete_related'))
1128    {
1129        $rel->delete_related($this);
1130    }

Does a delete_related method need to be added to my Post or Comments model?


Solution

  • Unset() doesn't delete the related object, it unsets the relation between the two.

    In case of a many-many, this will also mean the record in the junction table linking the two will be deleted, in other relations the foreign key will be reset to NULL.

    Both operations don't alter the data of the object, so an UPDATE will not be triggered on the object, and therefore the observers will not be called.

    "cascade" means that if you delete an object, the delete will "cascade" to the related object, deleting that too. But only if you delete the "parent" in the relation, not when you unset it (which doesn't delete anything).