matryoshkadoll / matryoshka-server

Laravel backend powering the Matryoshka website and API
https://matryoshkadoll.me
0 stars 2 forks source link

Make database seeders only run once #29

Closed shevtsod closed 5 years ago

shevtsod commented 5 years ago

We should modify the seeders we wrote so that each one of them only runs once. The current problem is that if we ever add new seeders that we need to run, we would end up creating duplicates of database records.

i.e.,

# AndroidApps, Reviews, Replies, etc. are seeded once
php artisan db:seed

# AndroidApps, Reviews, Replies, etc. are seeded again, one duplicate of each in database
php artisan db:seed

# AndroidApps, Reviews, Replies, etc. are seeded again, two duplicates of each in database
php artisan db:seed

# ...

But we want this:

# AndroidApps, Reviews, Replies, etc. are seeded once
php artisan db:seed

# Only records that don't exist yet are seeded, records that already exist are skipped
php artisan db:seed

# Only records that don't exist yet are seeded, records that already exist are skipped
php artisan db:seed

# ...

For example, here is a Voyager seeder that only runs once and here is one of our seeders that will always run.

So, we need to make a change like this for every object being seeded:

From:

DB::table('android_apps')->insert([
  [
    'name' => "App 1",
    'version' => "1.0",
    'description' => "Placeholder application 1",
    'price' => 0.00,
    'avatar' => "empty",
  ]
]);

To:

$androidApp= AndroidApp::firstOrNew(['name' => "App 1"]);

if (!$role->exists) {
  $role->fill([
    'version' => "1.0",
    'description' => "Placeholder application 1",
    'price' => 0.00,
    'avatar' => "empty",
  ])->save();
}
shevtsod commented 5 years ago

@oscar666666 Can you please handle this one?

oscar666666 commented 5 years ago

fixed