【问题标题】:Laravel: Integrity Constraint violation only on pre-productionLaravel:仅在预生产时违反完整性约束
【发布时间】:2020-03-16 11:48:24
【问题描述】:

我已经为此苦苦挣扎了一段时间,但没有找到任何东西。我希望你能帮助我。

我在 Lumen 有一个带有一些数据库的本地环境,并且我也有一些测试来检查 API。在本地,一切正常。我什至检查了几台电脑,一切正常。问题是当我将它上传到我们的预生产环境时,测试失败了。

预生产环境正在运行 PHP 7.3Laravel 6.4.0MySQL 5.7alpine Linux >

这是失败的测试之一:

    public function testUserSearch() {

    $userA = factory(User::class)->create();

    $userB = factory(User::class)->create();

    $url = '/api/users/search?name=' . $userA->name;

    echo $userA;

    $this->actingAs($userA, 'api')->get($url)
        ->assertJsonFragment(['id' => $userA->id])
        ->assertJsonMissing(['id' => $userB->id])
        ->assertStatus(200);

}

用户工厂:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => 'password',
        'api_token' => Str::random(60),
        'language' => 'es',
        'role_id' => 1,
        'remember_token' => Str::random(10),
   ];

});

“用户”表迁移:

    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('language')->default('es');
        $table->string('place')->nullable();
        $table->string('category')->nullable();
        $table->boolean('checkin_notification')->default(false);
        $table->unsignedBigInteger('role_id')->default(self::DEFAULT_ROLE);
        $table->rememberToken();

        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade')->onUpdate('cascade');
        $table->timestamps();
    });

“角色”表:

    Schema::create('roles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('ident')->unique();
        $table->text('description');
        $table->boolean('active')->defualt(0);
        $table->integer('level')->default(99);
        $table->timestamps();
    });

我得到的错误是:

提前谢谢你!

【问题讨论】:

  • role_id = 1. 这个值是真的吗?
  • 这意味着,roles 表没有任何 id 为 1 的行。确保角色表有数据将 role_id 外键链接到 users 表。
  • 是的,角色表有一个 id 为 1 的值,我已经检查过了。我有这个是因为它是我使用的默认角色,而且它始终是我在播种器中创建的第一个角色。

标签: php laravel


【解决方案1】:

创建角色工厂并尝试一下

    $factory->define(User::class, function (Faker $faker) use ($factory) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => 'password',
        'api_token' => Str::random(60),
        'language' => 'es',
        'role_id' => $factory->create(Role::class)->id,
        'remember_token' => Str::random(10),
   ];

【讨论】:

  • 我会尽快尝试。谢谢
  • 太棒了! @GiovanniCabrera
猜你喜欢
  • 2019-04-12
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 2017-09-11
  • 2020-06-14
相关资源
最近更新 更多