laravel-nestedset icon indicating copy to clipboard operation
laravel-nestedset copied to clipboard

Deleting node throws "Model must be node" exception when descendants are deleted

Open jengel3 opened this issue 5 years ago • 3 comments

Not sure what's going on here --

I've got a MenuItem class that represents the items in a tree-like navigation menu:

class MenuItem extends BaseModel
{
    use NodeTrait;

    protected $primaryKey = 'menu_item_id';
    protected $fillable = ['menu_item_id', 'left', 'right', 'parent_item_id', 'grouping_id'];
    protected $table = 'store_menu_items';

    public function getLftName ()
    {
        return 'left';
    }

    public function getRgtName ()
    {
        return 'right';
    }

    public function getParentIdName ()
    {
        return 'parent_item_id';
    }
}

Now, when I go to delete a node say $node = MenuItem::query()->find($someId); $node->delete() .. the node itself is deleted, but throws an exception when it tries to delete descendants.

However, if I call $node->deleteDescendants() then all the descendants are deleted without error, and of course the node itself is still present. If I call $node->delete() after doing that, the previous error is still thrown. I'm not sure why calling deleteDescendants() directly wouldn't throw that same error, considering that the deleted event linked above is going to call the exact same method eventually.

I've tracked it down to NestedSet::isNode(..) here which seems to return false when checking if the NodeTrait class is being used by the model.. which it clearly is in the above code. If I change that method to use PHP's class_uses method then the trait is definitely included in the outputted array, but for whatever reason isn't when it's being casted to an array in isNode(..).

Any idea what would be causing this? Could it be that I'm not using the typical primary keys or nestedset column names? I feel like a PR to use the class_uses method would solve this, but it seems to work for everyone else so I'm not sure why this is an issue in my code.

jengel3 avatar Apr 01 '19 17:04 jengel3

Maybe #157 is related?

jengel3 avatar Apr 01 '19 17:04 jengel3

This patch solved problem for me

Nenderus avatar Apr 17 '19 10:04 Nenderus

Error still present, the NestedSet::isNode($model) method is resolving to false but the model is using the NodeTrait class.

Edit: I was able to bypass this problem adding the attribute protected $nodeTraitClass = NodeTrait::class; to the Model, Using this way it is not necesary to edit the composer package.

jota0222 avatar Sep 17 '20 21:09 jota0222