这就是问题所在。我已经为此绞尽脑汁好几个小时了。Laravel不允许我有主键(它说有多个,但你可以看到它只有一个)。此外,由于教师表中主键存在问题引起的。我不能用这个作为课程表中的外键。
教师表的迁移文件
class CreateTeachersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('teachers', function (Blueprint $table) {
$table->increments('teacher_id')->primary();
$table->string('email', 200);
$table->string('first_name',300)->nullable();
$table->string('last_name',300)->nullable();
$table->string('account_status',50)->default('inactive');
$table->string('subscription_status',50);
$table->string('account_reset_code',400)->nullable();
$table->string('passkey',500);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('teachers');
}
}
课程表的迁移文件
class CreateCoursesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->increments('course_id')->primary();
$table->integer('teacher_id_fr');
$table->string('course_name', 500);
$table->string('course_code',300);
$table->string('subject_area',300);
$table->string('course_level',100);;
$table->string('grade_periods',100);
$table->timestamps();
});
Schema::table('courses',function(Blueprint $table){
$table->foreign('teacher_id_fr')->references('teacher_id')->on('teachers')->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('courses');
}
}
迁移时出现的问题
语法错误或访问冲突。1068找到多个主密钥
我现在尝试了什么
1)使用unsigned方法使主列无符号。
2)使用InnnoDB引擎类型作为表。
3)对于论坛上的类似帖子,还有很多其他建议,但似乎对我不起作用。
编辑
我已经从$table->increments('eacher_id')的两个文件中删除了primary()方法。正如所说,Laravel将自动递增列标记为主键。
但现在错误出现在课程表上。
一般错误:1215无法添加外键约束
您可以在迁移文件中定义多个主密钥,如下所示:
$table->primary(array('field_name1', 'field_name2'));
尝试替换此,删除primary()
,increments
自动创建它primary
$table->increments('teacher_id')->primary();
至
$table->increments('teacher_id');
对于新错误,请尝试此General error : 1215 cannot add foreign key constraint
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->increments('course_id');
$table->integer('teacher_id_fr');
$table->string('course_name', 500);
$table->string('course_code',300);
$table->string('subject_area',300);
$table->string('course_level',100);;
$table->string('grade_periods',100);
$table->timestamps();
$table->foreign('teacher_id_fr')
->references('teacher_id')->on('teachers')
->onDelete('cascade')
->onUpdate('cascade');
});
}
我只做了一分钟的更改就解决了这个问题。我修改了如下的课程迁移文件,它就像一个魅力
$table -> integer('teacher_id_fr') -> unsigned();
原因
实际上,被引用列和引用列(在本例中为teacher.teacher_id和course.teacher_id_fr)必须是同一类型。
话虽如此,Laravel将自动递增列标记为"Primary",并且类型为unsigned。因此,请确保更改foregin键列以匹配主键的类型,即unsigned。上述修改是这样做的。
希望它能澄清问题和解决方案。如果你还有别的想法。请在这里试一试。
快乐学习!