Summer Sale! All accounts are 50% off this week.

mstdmstd's avatar

How in migration to skip repeated rows?

In Laravel 8 I have seeder like :

$photoNominations = PhotoNomination::factory()->count(15)->create([
]);

    

and Factory

class PhotoNominationFactory extends Factory
{
    protected $model = PhotoNomination::class;

    public function definition()
    {
        return [
            'photo_id' => $this->faker->randomElement(Photo::all())['id'],
            'nomination_id' => $this->faker->randomElement(Nomination::all())['id'],
        ];

    }
}

How can I get all rows without repeated by 2 fields photo_id and nomination_id ?

Thanks!

0 likes
5 replies
mabdullahsari's avatar

This is not possible using default Factory behavior.

You will have to keep an identity map in your seeder to regenerate the entity.

1 like
mabdullahsari's avatar

@mstdmstd There is no example, this is just some plain PHP checks you need to add in your seeder.

You could even manually list them if you need to ensure uniqueness.

mstdmstd's avatar

@mabdullahsari , in which way? To cancel adding row has public function definition( return false/null or some other way ?

PovilasKorop's avatar

@mstdmstd I would probably do it not as a separate factory/seeder for the pivot table, but immediately when seeding Photos or Nominations.

Example of PhotoSeeder:

$nominations = Nomination::pluck('id');
$faker = Faker\Factory::create();
$maxNominationsPerPhoto = 3;

Photo::factory(100)->create()->each(function($photo) use ($nominations, $faker) {
    $photo->nominations()->attach($faker->unique()->randomElements($nominations, rand(1, $maxNominationsPerPhoto)))
});

Please or to participate in this conversation.