php - 未创建外键
问题描述
我正在尝试在教师表中创建一个外键。迁移后,所有列都在那里,但没有创建外键
首先,我创建了两个表,用户表和课程表。
if(! Schema::hasTable('users')) {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->string('password');
$table->string('remember_token')->nullable();
$table->timestamps();
});
}
if(! Schema::hasTable('courses')) {
Schema::create('courses', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('slug')->nullable();
$table->text('description')->nullable();
$table->decimal('price', 15, 2)->nullable();
$table->string('course_image')->nullable();
$table->date('start_date')->nullable();
$table->tinyInteger('published')->nullable()->default(0);
$table->timestamps();
$table->softDeletes();
$table->index(['deleted_at']);
});
}
然后我用外键创建了另一个名为“老师”的表
if(! Schema::hasTable('teacher')) {
Schema::create('teacher', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('course_id')->unsigned();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->string('teachers_image')->nullable();
$table->text('education')->nullable();
$table->text('contact')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
迁移后我可以看到表在那里,但没有创建外键
解决方案
尝试这个
if(! Schema::hasTable('teacher')) {
Schema::create('teacher', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('course_id');
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->string('teachers_image')->nullable();
$table->text('education')->nullable();
$table->text('contact')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
推荐阅读
- javascript - react和apollo中graphql突变钩子的错误处理不起作用
- logging - .net 日志从 filebeat 到 logstash 多行正确格式
- symfony - EasyAdmin 表单选择框 EntityType 未填充
- jquery - 对集合中的所有项目只触发一次点击
- html - 在数字输入中显示带 2 位小数的数字
- apache - 使用 apache 部署 Django 频道 - 没有名为“频道”的模块
- arrays - 从引导程序修复模态(仅删除第一行)问题
- javascript - 有没有办法使用 CSS、jQuery 或 JavaScript 更改 setCustomValidity 的默认图标和文本格式?
- json - 如何以适当的大小压缩 JSON 文件?
- c - 如何使用预处理指令#define 定义新的头文件?