مرتضی صبیحی
5 سال پیش توسط مرتضی صبیحی مطرح شد
1 پاسخ

مشکل در ایجاد دسته بندی

سلام
وقتی میخوام insert کنم به ارور برمیخورم

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`forum`.`categories`, CONSTRAINT `categories_parent_id_foreign` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE) (SQL: insert into `categories` (`title`, `parent_id`, `user_id`, `slug`, `updated_at`, `created_at`) values (vue js, 0, 1, vue-js, 2019-03-12 20:41:18, 2019-03-12 20:41:18))

migration:

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug');

            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->unsignedInteger('parent_id');
            $table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');

            $table->timestamps();
        });

migration:

 Schema::create('categorizables', function (Blueprint $table) {
            $table->unsignedInteger('category_id');
            $table->unsignedInteger('categorizable_id');
            $table->string('categorizable_type');
        });

controller:

public function store(Request $request)
    {
        return auth()->user()->category()->create($request->all());
    }

User.php:

 public function category()
    {
        return $this->hasMany(Category::class);
    }

Category.php:

    protected $fillable = ['title', 'slug', 'user_id', 'parent_id'];

ثبت پرسش جدید
حسام موسوی
تخصص : طراح و برنامه نویس
@hesammousavi 5 سال پیش مطرح شد
1

سلام نباید parent_id رو به شکل زیر رابطه ثبت کنید چون اگر صفر باشه نمیتونه اطلاعاتی پیدا کنه و بهش متصل بشه برای همین چنین اروری بر میگرد

$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');

این خط رو پاک کنید


برای ارسال پاسخ لازم است وارد شده یا ثبت‌نام کنید

ورود یا ثبت‌نام