PDOException::(“ SQLSTATE [HY000]:一般错误:1215无法添加外键约束”)

时间:2019-11-30 14:45:05

标签: sql laravel foreign-keys laravel-6.2

我正在使用laravel 6.2,连接是SQL。我正在创建两个表,具有“一对多关系”。表“用户”和“经理”,其中每个用户将有一个经理,而每个经理将有一个以上用户。

下面是用户表迁移:

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->integer('totalBalance')->default(21);
            $table->integer('annualBalance')->default(15);
            $table->integer('casualBalance')->default(6);
            $table->timestamps(); 


        });

        Schema::table('users', function (Blueprint $table) {
            $table->bigInteger('manager_id')->unsigned()->index();
            $table->foreign('manager_id')->references('id')->on('managers')
            ->onDelete('cascade');

        });


    }



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

下面是管理者迁移表:

<?php

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

class CreateManagersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('managers', function (Blueprint $table) {

            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();   
        });
    }



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

下面是用户模型:

<?php

namespace App;


use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements JWTSubject

{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

     // Rest omitted for brevity
    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
    public function setPasswordAttribute($value) {
        $this->attributes['password'] = bcrypt($value);
    }

    public function manager()
    {
        return $this->belongsTo('App\Manager');
    }
}

下面是经理模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Manager extends Model
{
    protected $primaryKey = 'id';

    public function users()
    {
        return $this->hasMany('App\User');
    }
}

我收到以下错误:

enter image description here

我尝试了很多事情,我在网上的其他问题中也看到过,包括更改id的类型(从BigInteger和integer,以及将database.php中的引擎更改为“ InnoDB”,以及将用户模型拆分为两部分(第二部分用于添加外键)。

我在网上看到的一件事(但没有弄清楚如何实现)是更改时间戳的顺序,因为其他人认为此错误可能与此有关。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为在创建经理表之前先进行了用户迁移。因此,使用以下内容更改迁移将有助于您在manager表下创建外键。

// user migration file

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->integer('totalBalance')->default(21);
            $table->integer('annualBalance')->default(15);
            $table->integer('casualBalance')->default(6);
            $table->timestamps(); 
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}


// managers migration file

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

class CreateManagersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('managers', function (Blueprint $table) {

            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();   
        });       

        Schema::table('users', function (Blueprint $table) {
            $table->bigInteger('manager_id')->unsigned()->index();
            $table->foreign('manager_id')->references('id')->on('managers')
            ->onDelete('cascade');
        });
    }



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