【发布时间】:2020-01-23 08:14:11
【问题描述】:
我创建了一个名为“users”的表。有名为“companies”、“designations”、“departments”的表。我想将 company_id、designation_id、department_id 列作为外键添加到 users 表中。
我试过了,但是没用
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('department_id');
$table->integer('company_id');
$table->integer('designation_id');
$table->foreign('department_id')->references('id')->on('departments')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('designation_id')->references('id')->on('designations')->onDelete('restrict')->onUpdate('restrict');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['department_id','company_id','designation_id']);
});
}
当我迁移迁移时,它会显示此错误。
Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般 错误:1005 无法创建表
lanwadb.users(errno: 150 "Foreign 键约束格式不正确”)(SQL:alter tableusersadd 约束users_department_id_foreign外键(department_id) 引用departments(id) 上删除限制更新限制)
指定迁移如下,
public function up()
{
Schema::create('designations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestampsTz();
});
}
部门迁移如下,
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('company_id');
$table->timestampsTz();
});
}
```
【问题讨论】:
-
首先你应该使用
unsignedInteger作为你的外键......特别是如果你将departments、company和designation表ID设置为increment字段..请还发布其他迁移,以便我们以更精确的方式为您提供帮助......但通常当Foreign key constraint is incorrectly formed被抛出时,这是因为 2 列的格式不同 -
@IlGala 是的,我已经为部门、公司和职务使用了增量字段。
标签: laravel foreign-keys migration