用户代码
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('user_role')->onDelete('cascade');
$table->rememberToken();
$table->timestamps();
});
}
用户角色代码
public function up()
{
Schema::create('user_roles', function (Blueprint $table) {
$table->increments('id');
$table->string('user_role');
$table->timestamps();
});
}
SQLSTATE[HY000]:一般错误:1005 无法创建表sms
。#sql-1718_62
(errno: 150 "外键约束的格式不正确") (SQL: alter table users
add constraint users_role_id_foreign
foreign key ( role_id
) 引用user_role
( id
) 在删除级联上)
如果你想引用一个外键,请不要用
$table->integer('role_id')->unsigned();
相反,你应该使用
$table->unsignedInteger('role_id');
这与 Migrations Part: Laravel Migrations 中的文档有关。
所以你的新语句最终应该看起来像
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->unsignedInteger('role_id');
$table->foreign('role_id')->references('id')->on('user_role')->onDelete('cascade');
$table->rememberToken();
$table->timestamps();
});
}
编辑:
作者添加了user_role表的迁移代码后,问题就清楚了。
作者所指的表称为user_roles而不是外键迁移user_role 中提到的。
所以这里是应该适用于用户表的迁移。
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->unsignedInteger('role_id');
$table->foreign('role_id')->references('id')->on('user_roles')->onDelete('cascade'); // change this line
$table->rememberToken();
$table->timestamps();
});
}
命名与 Laravel 命名约定有关,其中所有表都以复数命名,而所有模型都以单数命名。
编辑2:
OP提到他的迁移顺序错误,迁移不工作的原因是什么。
在用户表得到了之前创建user_roles表。这就是外键导致错误的原因。
希望这可以帮助你!如果您有更多问题,请告诉我!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句