【发布时间】:2018-08-01 21:50:12
【问题描述】:
我正在使用 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]: 一般错误: 1005 无法创建表
exam_paper.#sql-b88_630(errno: 150 "外键 约束格式不正确”)(SQL:alter tableanswersadd 约束answers_paper_foreign外键 (paper) 引用exampapers(paper_id))
我参考了大多数其他帖子,并且已经尝试过unsignedInteger() 数据类型,在创建外键之前运行表创建。
我在代码中做错了什么?
【问题讨论】:
-
你是先创建
exampapers表再创建answers吗?另外,在answers表中添加两个外键。如果你不明白,请告诉我! -
@HirenGohel 我照你说的做了还是错误,Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误:1005 无法创建表
exam_paper.#sql-b88_63d(errno: 150 "外键约束格式不正确”)(SQL:更改表answers添加约束answers_paper_foreign外键(paper)引用exampapers(paper_id)) -
添加
$table->integer('paper_id')->unsigned()->nullable()->index();和$table->text('question')->unsigned()->nullable()->index(); -
@HirenGohel 感谢它在添加
->nullable()->index()后有效 -
很高兴能帮到你!!我已经发布了我的答案!
标签: mysql laravel foreign-keys migration