【问题标题】:errno: 150 "Foreign key constraint is incorrectly formed")errno: 150 "外键约束格式不正确")
【发布时间】: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


【解决方案1】:

$table->foreign('email')->references('email')->on('profile');

您的用户模型:

public function profile()
{
  return $this->hasOne(Profile::class, 'email', 'email');
}

您的个人资料模型:

public function user()
{
    return $this->belongsTo(User::class);
}

【讨论】:

  • 感谢您的解决,但仍然无法解决问题。
【解决方案2】:

外键列是 STRING unique(),而引用的列是 PRIMARY 类型而不是 STRING 类型。在您的个人资料表中,您有两列名称相同但类型不同。

表配置文件

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'); <--------You have a mix up here. The column should be $table->primary('id')
});

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 2018-03-02
    • 1970-01-01
    • 2017-04-13
    • 2018-09-04
    • 2019-09-17
    • 2020-12-16
    • 2019-09-15
    相关资源
    最近更新 更多