【发布时间】:2020-07-07 00:00:59
【问题描述】:
任何人都可以从以下错误消息“errno:150”外键约束格式错误“)”中给我一个解决方案吗?当我想使用 email 属性创建从用户表到配置文件表的外键时会出现问题,其中配置文件表中的主键是电子邮件本身。
表用户
Schema::create('users', function (Blueprint $table) {
$table->bigInteger('id', 20)->autoIncrement();
$table->string('id_provider', 20)->nullable();
$table->string('provider_name', 255);
$table->string('email', 255)->unique();
$table->foreign('email', 255)->references('email')->on('profile')->onDelete('cascade');
$table->timestamp('email_verified_at')->nullable();
$table->string('password', 255)->nullable();
$table->string('role', 12);
$table->rememberToken();
$table->timestamps();
$table->primary('id');
});
模型用户
/**
* Get the profile record associated with user.
*/
public function profile()
{
return $this->hasOne('App\Profile');
}
标签配置文件
Schema::create('profile', function (Blueprint $table) {
$table->string('email', 255)->unique();
$table->string('name', 255);
$table->integer('phone_number', 12)->nullable();
$table->string('gender', 6)->nullable();
$table->integer('date', 2)->nullable();
$table->string('month', 9)->nullable();
$table->integer('year', 4)->nullable();
$table->bigInteger('id_address', 20)->nullable();
$table->string('avatar', 100);
$table->primary('email');
});
模型简介
/**
* Get the user that owns the profile.
*/
public function user()
{
return $this->belongsTo('App\User');
}
感谢您提供的所有解决方案。
【问题讨论】:
-
您是使用迁移还是手动进行?
-
使用迁移
-
外部调用引用了一个列。您不需要在其末尾添加“,255”,因为您已经在 string("email", 255)" 列中设置了它。
-
配置文件迁移是否在用户迁移之前运行?
-
是的,正是……
标签: php mysql laravel eloquent foreign-keys