Skip to content

Soft Delete error while restoring related models with cascade_delete = true #338

@mayismile

Description

@mayismile

I have the model User with HasOne relations Profile and Balance. Both of these relations have

'cascade_delete' = true

Deleting runs good, but restoring User model and both related models throws an error Call to a member function restore() on a non-object in a /packages/orm/classes/model/soft.php line 240

The code is

public function restore($cascade_restore = null)
{
    $deleted_column = static::soft_delete_property('deleted_field', static::$_default_field_name);
    $this->{$deleted_column} = null;

    //Loop through all relations and delete if we are cascading.
    $this->freeze();
    foreach ($this->relations() as $rel_name => $rel)
    {
        //get the cascade delete status
        $rel_cascade = is_null($cascade_restore) ? $rel->cascade_delete : (bool)$cascade_restore;

        //Make sure that the other model is soft delete too
        if ($rel_cascade)
        {
            if (! is_subclass_of($rel->model_to, 'Orm\Model_Soft'))
            {
                //Throw if other is not soft
                throw new RelationNotSoft('Both sides of the relation must be subclasses of Model_Soft if cascade delete is true');
            }

            if (get_class($rel) != 'Orm\ManyMany')
            {
                $model_to = $rel->model_to;
                $model_to::disable_filter();

                //Loop through and call restore on all the models
                foreach ($rel->get($this) as $model)
                {
                    $model->restore($cascade_restore); // I checked and this var $model is null
                }

                $model_to::find_deleted($this->{$rel->key_from[0]})->restore($cascade_restore);

                $model_to::enable_filter();
            }
        }
    }
    $this->unfreeze();;

    return $this->save();
}

So, may be I'm wrong with this point, but I changed this code part

//Loop through and call restore on all the models
foreach ($rel->get($this) as $model)
{
    $model->restore($cascade_restore); // I checked and this var $model is null
}

to this one

$model_to::find_deleted($this->{$rel->key_from[0]})->restore($cascade_restore);

and everything started to work fine.

May be I used Soft Delete wrongly?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions