1005 无法创建 table `portal`.`employees`(错误号:150 "Foreign key constraint is incorrectly formed")”)

1005 Can't create table `portal`.`employees` (errno: 150 "Foreign key constraint is incorrectly formed")")

嘿伙计们,我尝试了太多东西并阅读了一些博客或讨论我没有解决我的问题我是 laravel 这个项目的新手。当我想创建数据库时出现错误

PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `portal`.`employees` (errno: 150 "Foreign key constraint is incorrectly formed")")

我的付款迁移:

  public function up()
{
    Schema::create('payments', function (Blueprint $table) {
        $table->bigInteger('id');
        $table->unsignedBigInteger('employee_id');
        $table->decimal('salary',16);
        $table->decimal('amount_paid',16);
        $table->unsignedBigInteger('paid_by');
        $table->string('remark');
        $table->string('department',50);
        $table->timestamps();
    });
    Schema::table('payments', function($table) {
        $table->foreign('employee_id')->references('id')->on('employees')->onUpdate('cascade')->onDelete('cascade');

        $table->foreign('paid_by')->references('id')->on('users');
    });
}

我的员工迁移:

    public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->unsignedBigInteger('id');
        $table->string('name');
        $table->string('department');
        $table->string('location');
        $table->string('telephone');
        $table->decimal('salary',16);
        $table->string('cover_image');
          $table->foreign('department')->references('name')->on('departments')->onUpdate('cascade')->onDelete('cascade');
        $table->timestamps();
    });

部门Table:

   public function up()
{
    Schema::create('departments', function (Blueprint $table) {
        $table->bigInteger('id');
        $table->string('name');
        $table->timestamps();
    });
}

我的迁移文件夹: https://i.stack.imgur.com/pCsbg.png

你可以简单地在部门ID上设置外键,当然,在唯一键上设置外键会更好,性能也会更好。

在非唯一列上制作外键不是一个好主意,只有 mysql 的 innodb 支持,请参阅 mysql doc

而不是:

  $table->foreign('department')->references('name')->on('departments')->onUpdate('cascade')->onDelete('cascade');

你应该像这样定期创建外键:

 $table->bigInteger('department_id');
 $table->foreign('department_id')->references('id')->on('departments')->onUpdate('cascade')->onDelete('cascade');