我正在尝试向我的用户表添加一个Permission_id外键,该外键将引用我的权限表中的ID。目前,我建立了以下迁移:
<?php
class AddPermissionIdForeignKeyToUsersTable extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('permission_id')->after('id');
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('permission_id');
});
}
}
但是出现以下错误:
SQLSTATE [23000]:违反完整性约束:1452无法添加或 更新子行:外键约束失败 ({
eyes
。#sql-22f0_3dd
,约束users_permission_id_foreign
外键(permission_id
)参考p ermissions
(id
)开启 DELETE CASCADE)(SQL:更改表users
添加约束users_permission_id_foreign
个外键(permission_id
)引用permissions
(id
)在删除级联上)在PDOStatement.php第144行中:
SQLSTATE [23000]:违反完整性约束:1452无法添加或 更新子行:外键约束失败 ({
eyes
。#sql-22f0_3dd
,约束users_permission_id_foreign
外键(permission_id
)参考p ermissions
(id
)开启 删除级联)在PDOStatement.php第142行:
SQLSTATE [23000]:违反完整性约束:1452无法添加或 更新子行:外键约束失败 ({
eyes
。#sql-22f0_3dd
,约束users_permission_id_foreign
外键(permission_id
)参考p ermissions
(id
)开启 删除级联)
答案 0 :(得分:0)
如果您的表用户中已经有数据,则需要将您的字段Permission_id声明为可空。
$table->unsignedInteger('permission_id')->nullable()->after('id');