php - 不能在新表 Laravel 5.8 上添加外键
问题描述
我有两个表,例如 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,但仍然错误。我正在使用-> 可为空的。但没用。有人能找到这个错误吗?
编辑 。这个错误:
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束(SQL:alter table
users
添加约束users_roles_id_foreign
外键(roles_id
)引用roles
(id
))
解决方案
首先,创建角色表:
public function up(){
Schema::create('roles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('roles');
$table->timestamps();
});
}
然后创建一个用户表:
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')->nullable();
$table->foreign('roles_id')->references('id')->on('roles');
$table->timestamps();
$table->softDeletes();
});
}
对于删除外键:
Schema::table('users', function (Blueprint $table) {
$table->dropForeign('users_roles_id_foreign');
$table->dropColumn('roles_id');
});
推荐阅读
- arrays - PostgreSQL 中数组搜索的替代解决方案
- python - 如何在服务器中部署/存储 tkinter sqlite 数据库?
- amazon-web-services - AWS Pinpoint 交易电子邮件:如何包含退订链接?
- python - Telegram bot run_repeating 与 python-telegram-bot 库
- python - 使用已编译的 pyc 模块的 setup.py 的 ModuleNotFoundError
- google-cloud-platform - 如何在没有终端的 GCP 上直接使用 Tensorboard?
- java - 无法删除集合行:列索引超出范围
- python - AWS Glue Spark 作业错误:“ModuleNotFoundError:您需要使用 sqlserver 分别安装 pyodbc AWS Data Wrangler 包”
- javascript - 尝试连接到 MongoDB 数据库时出现此错误
- javascript - 突出显示并制作可点击的非常规区域?