[英]laravel migration error while adding 2 foreign key
我正在使用 Laravel 迁移来创建我的 MySQL 数据库,并且有两个表论文和答案,并且需要使用外键连接两个表。 我有paper_id
以及question_no
作为外键。 但是在添加外键时出现错误。 我的纸表和答案表的迁移
Schema::create('exampapers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper_id');
$table->integer('question_no');
$table->text('question');
$table->string('answer1');
$table->string('answer2');
$table->string('answer3');
$table->string('answer4');
$table->integer('answerC');
$table->string('knowarea');
$table->timestamps();
$table->index(['paper_id','question_no']);
});
Schema::create('answers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper')->unsigned();
$table->integer('question')->unsigned();
$table->integer('answers');
$table->timestamps();
});
这是我创建外键的代码,
Schema::table('answers',function($table){
$table->foreign('paper')->references('paper_id')->on('exampapers');
$table->foreign('question')->references('question_no')->on('exampapers');
});
我通过 php artisan 得到的错误是,
Illuminate\\Database\\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table
exam_paper
。#sql-b88_630
(errno: 150 "外键约束#sql-b88_630
不正确") (SQL: alter tableanswers
添加约束answers_paper_foreign
外键 (paper
) 参考exampapers
(paper_id
))
我参考了其他大部分帖子,并且已经尝试过unsignedInteger()
数据类型,在创建外键之前运行表创建。
我的代码做错了什么?
您需要添加->unsigned()->nullable()->index();
在两列中(即在paper_id
和exampapers
表中的question
)。
尝试在exampapers
表中添加如下exampapers
:
$table->integer('paper_id')->unsigned()->nullable()->index();
$table->integer('question_no')->unsigned()->nullable()->index();
现在运行php artisan migrate
并修复问题!
希望这对你有帮助!
您还需要使exampapers
表中的密钥未签名:
$table->integer('paper_id')->unsigned();
或者:
$table->insignedInteger('paper_id');
或者从外键定义中删除unsigned()
方法:
$table->integer('paper');
我对您的迁移代码进行了一些编辑。 希望这会奏效
Schema::create('exampapers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper_id')->unsigned()->index();
$table->integer('question_no')->unsigned()->index();
$table->text('question');
$table->string('answer1');
$table->string('answer2');
$table->string('answer3');
$table->string('answer4');
$table->integer('answerC');
$table->string('knowarea');
$table->timestamps();
//$table->index(['paper_id','question_no']);
});
Schema::create('answers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('paper')->unsigned()->index();
$table->integer('question')->unsigned()->index();
$table->integer('answers');
$table->timestamps();
});
Schema::table('answers',function($table){
$table->foreign('paper')->references('paper_id')->on('exampapers');
$table->foreign('question')->references('question_no')->on('exampapers');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.