skip to Main Content

I have a table migration with a unique condition on item_id and user_id fields:

Schema::create('item_user', function (Blueprint $table) {
    $table->id();
    $table->foreignId('item_id')->references('id')->on('items')->onUpdate('RESTRICT')->onDelete('CASCADE');
    $table->foreignId('user_id')->references('id')->on('users')->onUpdate('RESTRICT')->onDelete('CASCADE');

    $table->boolean('active')->default(false);
    $table->date('expires_at')->nullable();
    $table->timestamps();

    $table->unique(['item_id', 'active', 'user_id'], 'item_item_id_active_user_id_index');
});

I got error duplicate entry on item_id and user_id fields with factory.

class ItemUserFactory extends Factory
{
    public function definition()
    {
        return [
            'user_id' => $this->faker->randomElement(User::all())['id'],
            'item_id' => $this->faker->randomElement(Item::all())['id'],
            'active' => $this->faker->randomElement([0, 1]),
            'expires_at' => $this->faker->dateTimeBetween('2 days', '1 month')
        ];
    }

How can I fix it?

"laravel/framework": "^10.34.2",
"fakerphp/faker": "^1.23.0",

2

Answers


  1. Set the user relation in the item model class and then in the factory try this:

    public function definition()
    {
        return [
                 //...
                'item_id' => $this->faker->randomElement(Item::doesntHave('user')->get())['id']
        ];
    }
    
    Login or Signup to reply.
  2. class ItemUserFactory extends Factory
    {
        public function definition()
        {
            // Ensure unique combination of item_id, active, and user_id
            return [
                'user_id' => User::factory(),
                'item_id' => Item::factory(),
                'active' => $this->faker->randomElement([0, 1]),
                'expires_at' => $this->faker->dateTimeBetween('2 days', '1 month')
            ];
        }
    }
    

    User::factory() and Item::factory() methods provided by Laravel to create new instances of User and Item models. These methods will automatically handle the creation and persistence of unique records. Make sure you have the corresponding model factories (UserFactory and ItemFactory) defined.

    Additionally, you might need to make sure that the factories for User and Item also generate unique records. If these factories don’t already have the unique constraint, you should add it to their definitions as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search