问题描述
Schema::create('type_adhs',function (Blueprint $table) {
$table->increments('id_typeAdh');
$table->string('libelle',120)->unique();
$table->text('description')->nullable();
$table->timestamps();
});
Schema::create('users',function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->string('prenom');
$table->string('tel_personnel');
$table->string('tel_prof');
$table->enum('societe',['x','y']);
$table->enum('titre_civilite',['Mr','Mrs']);
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('typeAdh_id');
$table->foreign('typeAdh_id')->references('id_typeAdh')->on('type_adhs')->onDelete('cascade');
$table->rememberToken();
$table->timestamps();
});
ErrorMessage : sqlSTATE[HY000]: 一般错误: 1215 无法添加外键约束 (sql: 更改表 users
添加约束 users_typeadh_id_foreign
外键 (typeAdh_id
) 引用 {{1} } (type_adhs
) 在删除级联上)
解决方法
我相信 Laravel the increments() method produces an unsigned integer。
但是您在 users 表中添加了 typeAdh_id 作为有符号整数。您不能将其设为引用父表的未签名主键的外键。
所以你应该让它成为一个无符号整数来匹配:
$table->unsignedInteger('typeAdh_id');
$table->foreign('typeAdh_id')->references('id_typeAdh')->on('type_adhs')->onDelete('cascade');
,
从用户迁移中删除 $table->integer('typeAdh_id');
。
并使用 $table->foreignId('typeAdh_id')->references('id_typeAdh')->on('type_adhs')->onDelete('cascade');
只需在 'foreign' 后添加 'Id',所以它是 foreignId
。
使您的 typeAdh_id 在 users 表中未签名:
$table->integer('typeAdh_id')->unsigned()->nullable();
$table->foreign('typeAdh_id')->references('id_typeAdh')->on('type_adhs')->onDelete('cascade');