Laravel migration foreign key issue

后端 未结 2 732
悲&欢浪女
悲&欢浪女 2020-12-21 12:31

I have created categories table using categories migration and then i am trying to create products table using another migration with foreign key categories_id in products t

2条回答
  •  囚心锁ツ
    2020-12-21 12:39

    You may try this (Notice unsigned and references you have used reference):

    // unsigned() should be used during declaration
    $table->integer('category_id')->unsigned();
    
    // reference() should be references()
    $table->foreign('category_id')->references('id')->on('categories');
    

    Update:

    At first create the products table then add foreign key. Remove the following line when creating the table:

    $table->foreign('category_id')->references('id')->on('categories');
    

    Then add foreign key using this:

    Schema::table('products', function($table) {
        $table->foreign('category_id')->references('id')->on('categories');
    });
    

    Both should be different like this:

    Schema::create('products', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->string('product_name');
        // more ...
    });
    
    Schema::table('products', function($table) {
        $table->foreign('category_id')->references('id')->on('categories');
    });
    

提交回复
热议问题