【发布时间】:2016-11-21 15:50:09
【问题描述】:
我正在尝试创建 char 数据类型的可空外键。当我运行迁移命令时。我收到以下错误。我不确定,我在哪里做错了。
[Illuminate\Database\QueryException] SQLSTATE[HY000]:一般错误: 1215 无法添加外键约束(SQL:alter table
levelsadd 约束levels_sample_type_id_foreign外键 (sample_type_id) 引用sample_types(id))[PDOException] SQLSTATE[HY000]: 一般错误: 1215 无法添加外部 关键约束
这是levels表的迁移文件内容
public function up()
{
Schema::create('levels', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->char('id', 36)->unique();
$table->string('description')->nullable();
$table->char('sample_type_id', 36)->nullable();
$table->integer('order');
$table->timestamps();
$table->primary('id');
$table->foreign('sample_type_id')->references('id')->on('sample_types');
});
}
对于sample_types表如下
public function up()
{
Schema::create('sample_types', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->char('id', 36)->unique();
$table->string('name');
$table->timestamps();
$table->primary('id');
});
}
【问题讨论】:
-
sample_types.id列是什么类型? -
我相当肯定两者必须属于同一类型。所以
sample_type_id不能为空。 -
sample_types是在levels之前创建的? -
@miken32,你是对的。表级别是在 sample_types 之前创建的。我现在可以毫无问题地生成外键。谢谢你。您能否将此评论添加为答案?
标签: php mysql laravel laravel-migrations