在Laravel 5中播种数据库时的完整性约束违例

时间:2017-03-17 10:19:51

标签: php laravel laravel-5

我试图在Laravel 5中播种我的数据库。迁移成功但尝试种子时出错:

[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ict302`.`psas`, CONSTRAINT `psas_psa_user_
id_foreign` FOREIGN KEY (`psa_user_id`) REFERENCES `users` (`id`))

以下是我的迁移:

用户表:

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    Schema::dropIfExists('users');
    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}

PSA表:

public function up()
    {
        Schema::create('psas', function (Blueprint $table) {
            $table->increments('psa_id');
            $table->timestamps();
            $table->string('psa_email',50);
            $table->unique('psa_email');
            $table->string('psa_name', 30);
            $table->integer('psa_user_id')->unsigned()->onDelete('cascade');
        });

        Schema::table('psas', function (Blueprint $table)
        {
            $table->foreign('psa_user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        Schema::dropIfExists('psas');
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }

数据库播种机类:

public function run()
    {
        //Model::unguard();
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        $this->call(AccessTableSeeder::class);
        $this->call(HistoryTypeTableSeeder::class);

        $this->call(UserTableSeeder::class);
        $this->call(PsaTableSeeder::class);
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
        //Model::reguard();
    }

我做错了什么,如何解决?

1 个答案:

答案 0 :(得分:0)

@Gautam Nath

您可以尝试使用以下概念,例如:如果您希望user_id作为“psas'”中的外键。表然后定义如下内部向上功能。

$table->integer('user_id')->unsigned()->nullable();

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');