Laravel 迁移无法添加外键

问题描述 投票:0回答:5

我正在尝试编写 Laravel 数据库迁移,但收到以下关于外键的错误:

  [Illuminate\Database\QueryException]                                                                                                                                                                                                                    
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table (SQL: alter table `subcategories` add constraint subcategories_category_id_foreign foreign key (`category_id`) references `categories` (`id`))  



  [PDOException]                                                                                           
  SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table 

categories
subcategories
表确实已创建,但外键并未创建。这是我的迁移:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function ($table) {
            $table->increments('id')->unsigned();
            $table->string('name')->unique();
        });

        Schema::create('subcategories', function ($table) {
            $table->increments('id')->unsigned();
            $table->foreign('category_id')->references('id')->on('categories');
            $table->string('name')->unique();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('categories');
        Schema::drop('subcategories');
    }
}

有什么想法吗?谢谢!

mysql database laravel migration
5个回答
85
投票

您应该在创建外键之前创建列:

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

文档:http://laravel.com/docs/5.1/migrations#foreign-key-constraints


4
投票

Laravel 7、8

正如Limon Monte提到的,首先创建列,然后添加外键约束

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

2
投票

整数对我不起作用。相反,我使用 bigInteger 来创建外键:

$table->bigInteger('category_id')->unsigned()->index()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

0
投票

我忘记将

->get()
添加到我调用的方法中。


0
投票

只需使用

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

© www.soinside.com 2019 - 2024. All rights reserved.