Laravel迁移:错误号:150“外键约束格式不正确”

时间:2019-07-14 12:26:04

标签: database laravel migration mariadb

我收到错误

SQLSTATE[HY000]: General error: 1005 Can't create table posys .#sql-2b94_d2 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table purchase_orders add constraint Purchase_orders_status_id_foreign foreign key ( status_id ) references状态( id ))

运行迁移时。

这是我的移民:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStaffTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('staff', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('position')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('staff');
    }
}

还有

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePurchaseOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('purchase_orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->float('total_price_ex_vat', 12, 2);
            $table->float('total_price_inc_vat', 12, 2);
            $table->string('deliver_to'); 
            $table->unsignedBigInteger('staff_id'); // Foreign key
            $table->foreign('staff_id')->references('id')->on('staff');
            $table->unsignedBigInteger('supplier_id'); // Foreign key
            $table->foreign('supplier_id')->references('id')->on('suppliers');
            $table->unsignedBigInteger('status_id'); // Foreign key
            $table->foreign('status_id')->references('id')->on('statuses');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('purchase_orders');
    }
}

2 个答案:

答案 0 :(得分:0)

您的big int与未签名的big int不兼容:

$table->unsignedBigInteger('staff_id'); // on purchase orders

vs:

$table->bigIncrements('id'); // on staff

只需为staff_id使用常规的大整数,或者也将您员工的id取消签名

答案 1 :(得分:0)

为避免错误150,请选择一个:

  • 重新排列CREATE TABLEs
  • 的顺序
  • DISABLE FK,进行创建,然后启用它们。
  • 在所有ADD完成之前,不要CREATEs个FK。