我希望用户拥有像 user、admin、editor... 这样的等级,但是我无法将外键添加到 rank 表中 user 表中的 rank 列。
这是ranks表的迁移
Schema::create('ranks', function (Blueprint $table) {
$table->increments('id');
$table->string('rank', 32)->charset('utf8')->nullable($value = false);
});
这是用户表迁移
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 64)->charset('utf8')->nullable($value = false);
$table->string('email', 128)->unique()->charset('utf8')->nullable($value = false);
$table->string('password', 128)->charset('utf8')->nullable($value = false);
$table->integer('rank')->unsigned()->default(1);
$table->foreign('rank')->references('id')->on('ranks')->nullable($value = false);
$table->rememberToken();
$table->timestamps();
});
最佳答案
默认情况下,users
表迁移具有 2014_10_12_000000
时间戳,因此它是在任何手动创建的迁移之前创建的。因此,更改 ranks
表迁移文件名时间戳以在 users
表之前创建表。例如:
2013_10_12_000000_create_ranks_table.php
2014_10_12_000000_create_users_table.php
此外,将 FK 约束代码移动到单独的闭包中:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 64)->charset('utf8')->nullable($value = false);
$table->string('email', 128)->unique()->charset('utf8')->nullable($value = false);
$table->string('password', 128)->charset('utf8')->nullable($value = false);
$table->integer('rank')->unsigned()->default(1);
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->foreign('rank')->references('id')->on('ranks')->nullable();
});
关于php - Laravel 数据库外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48770886/