Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Integrity constraint violation error when deleting a node. #568

Open
Duddy67 opened this issue Dec 15, 2022 · 1 comment
Open

Integrity constraint violation error when deleting a node. #568

Duddy67 opened this issue Dec 15, 2022 · 1 comment

Comments

@Duddy67
Copy link

Duddy67 commented Dec 15, 2022

Hi,
I'm having a problem when I try to delete a node with descendants.

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post\Category;

class Post extends Model
{
    use HasFactory;

    ...


    /**
     * The categories that belong to the post.
     */
    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

    ...

}
namespace App\Models\Post;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Post;
use Kalnoy\Nestedset\NodeTrait;

class Category extends Model
{
    use HasFactory, NodeTrait;

    protected $table = 'post_categories';

    ...

    /**
     * The posts that belong to the category.
     */
    public function posts()
    {
        return $this->belongsToMany(Post::class);
    }


    public function delete()
    {
        $this->posts()->detach(); 
        parent::delete();
    }

    ...

}

When I delete a node that hasn't any descendant everything it's ok.

$category->delete();

Now when I try to delete a node that has one or more descendants I get this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`myproject`.`category_post`, CONSTRAINT `category_post_category_id_foreign` FOREIGN KEY (`category_id`) REFERENCES `post_categories` (`id`))
delete from `post_categories` where `post_categories`.`_lft` between 4 and 8

It looks like the Category delete() method is not called when the nested-set trait deletes the descendants.
How can I fix this issue, should I delete the descendant nodes manually ?

@fd6130
Copy link

fd6130 commented Apr 12, 2023

+1 same having this issue..

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants