【发布时间】:2021-03-05 14:57:33
【问题描述】:
我正在尝试使用 user_role 表在用户表中创建外键关系。
用户表迁移
user_role 列是外键列
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('user_role')->nullable();
$table->foreign('user_role')->references('role')->on("user_role")->onDelete('cascade');
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
用户角色表
public function up()
{
Schema::create("user_role",function(Blueprint $table){
$table->increments('id');
$table->string("role")->nullable();
});
}
迁移未应用以下错误正在生成
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1005 Can't create table `ecommerce`.`users` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `users` add constraint `users_user_role_foreign` foreign key (`user_role`) references `user_role` (`role`) on delete cascade)
at F:\ecommerce-indian\ecommerce\vendor\laravel\framework\src\Illuminate\Database\Connection.php:678
674▕ // If an exception occurs when attempting to run a query, we'll format the error
675▕ // message to include the bindings with SQL, which will make this exception a
676▕ // lot more helpful to the developer instead of just the database's errors.
677▕ catch (Exception $e) {
➜ 678▕ throw new QueryException(
679▕ $query, $this->prepareBindings($bindings), $e
680▕ );
681▕ }
682▕
1 F:\ecommerce-indian\ecommerce\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `ecommerce`.`users` (errno: 150 "Foreign key constraint is incorrectly formed")")
2 F:\ecommerce-indian\ecommerce\vendor\laravel\framework\src\Illuminate\Database\Connection.php:471
PDOStatement::execute()
我做错的外键有什么问题。
【问题讨论】:
-
您必须在第二个表的主键上创建外键。在您的情况下,将
user_role_id添加到将在user_role表中引用id的用户。 -
@V-K 谢谢它的工作,但有什么方法可以连接角色列
-
是的,有办法。检查我的回复。
-
@ManinderSingh,你不需要在
role上创建FK,因为两个表的字段相同,只是重复 -
将角色添加为唯一 $table->string("role")->unique();那会做到的。 @ManinderSingh