From 2fcabb949c74e2e22ee71fa45cd50a9706febd8c Mon Sep 17 00:00:00 2001 From: "Christopher C. Wells" Date: Tue, 30 Mar 2021 15:51:56 -0700 Subject: [PATCH] Use factories for BelongsTo relationships in factory --- .../factories/IngredientAmountFactory.php | 30 ++++++++----------- database/factories/JournalEntryFactory.php | 2 ++ 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/database/factories/IngredientAmountFactory.php b/database/factories/IngredientAmountFactory.php index bb1bf98..2e97342 100644 --- a/database/factories/IngredientAmountFactory.php +++ b/database/factories/IngredientAmountFactory.php @@ -21,32 +21,26 @@ class IngredientAmountFactory extends Factory */ public function definition(): array { - // @todo Remove these hard-corded create statements. - // See: https://laravel.com/docs/8.x/database-testing#factory-relationships - - /** @var \App\Models\Recipe $recipe */ - $recipe = Recipe::factory()->create(); - if ($this->faker->boolean(90)) { - /** @var \App\Models\Food $ingredient */ - $ingredient = Food::factory()->create(); - $unit = Nutrients::units()->pluck('value')->random(1)->first(); + $ingredient_factory = Food::factory(); + $ingredient_type = Food::class; + $ingredient_unit = Nutrients::units()->pluck('value')->random(1)->first(); } else { - /** @var \App\Models\Recipe $ingredient */ - $ingredient = Recipe::factory()->create(); - $unit = 'serving'; + $ingredient_factory = Recipe::factory(); + $ingredient_type = Recipe::class; + $ingredient_unit = 'serving'; } return [ - 'ingredient_id' => $ingredient->id, - 'ingredient_type' => $ingredient::class, + 'ingredient_id' => $ingredient_factory, + 'ingredient_type' => $ingredient_type, 'amount' => $this->faker->randomFloat(1, 1/3, 5), - 'unit' => $unit, + 'unit' => $ingredient_unit, 'detail' => $this->faker->optional(0.8)->realText(), - 'weight' => $this->faker->optional(0.8)->numberBetween(0, 50), - 'parent_id' => $recipe->id, - 'parent_type' => $recipe::class, + 'weight' => $this->faker->numberBetween(0, 50), + 'parent_id' => Recipe::factory(), + 'parent_type' => Recipe::class, ]; } diff --git a/database/factories/JournalEntryFactory.php b/database/factories/JournalEntryFactory.php index f81bf15..3f4e188 100644 --- a/database/factories/JournalEntryFactory.php +++ b/database/factories/JournalEntryFactory.php @@ -3,6 +3,7 @@ namespace Database\Factories; use App\Models\JournalEntry; +use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; class JournalEntryFactory extends Factory @@ -18,6 +19,7 @@ class JournalEntryFactory extends Factory public function definition(): array { return [ + 'user_id' => User::factory(), 'date' => $this->faker->dateTimeThisMonth, 'summary' => $this->faker->realText(50), 'calories' => $this->faker->randomFloat(2, 0, 500),