【发布时间】:2019-10-15 16:22:59
【问题描述】:
我有两个表,例如 User 和 Roles 。我想在 Table Users 上添加外部 Roles_id 。
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('NIK',16);
$table->string('nama');
$table->string('email')->unique();
$table->string('username');
$table->string('password');
$table->unsignedBigInteger('roles_id')->default(1);
$table->timestamps();
$table->softDeletes();
$table->foreign('roles_id')->references('id')->on('roles');
});
}
还有我的角色表
public function up()
{
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('roles');
$table->timestamps();
});
}
我没有捕捉到错过的代码,我使用 unsignedBigInteger,但仍然错误。 我正在使用 -> nullable 。但没有用。有人能找到这个错误吗?
编辑。这个错误:
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table
users添加约束users_roles_id_foreign外键(roles_id)引用roles(id))
【问题讨论】:
-
角色迁移是否在用户表迁移之前运行?
-
我先创建用户表。现在我有 2 个表 .users 和角色。我想让这个外国的。它的错误步骤?
-
如果你想在users表中创建role_id作为foreign,必须已经创建了roles表。您可以做的是在用户迁移文件时间戳之前更改角色的迁移文件时间戳。
-
好吧,看看我的步骤。我创建了用户表(在角色上没有 FK),现在我创建了角色表。(我现在有 2 个没有 FK 的表)。现在我在线程上添加了外国之类的。我运行 php artisan migrate 。并显示“Nothing to Migrate”
-
如果我运行 migrate:fresh 它的错误就像在这个线程上一样
标签: php laravel foreign-keys migration