65 lines
1.8 KiB
PHP
65 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace Database\Factories;
|
|
|
|
use App\Models\Chicken;
|
|
use App\Models\EggCollection;
|
|
use App\Models\EggCollectionItem;
|
|
use Illuminate\Database\Eloquent\Factories\Factory;
|
|
|
|
/**
|
|
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\EggCollection>
|
|
*/
|
|
class EggCollectionFactory extends Factory
|
|
{
|
|
protected $model = EggCollection::class;
|
|
|
|
public function definition(): array
|
|
{
|
|
$dateTime = $this->faker->dateTimeBetween('-1 month', 'now');
|
|
|
|
return [
|
|
'production_date' => $dateTime,
|
|
'total_eggs' => 0,
|
|
'notes' => $this->faker->optional(0.4)->sentence(),
|
|
];
|
|
}
|
|
|
|
public function configure()
|
|
{
|
|
return $this->afterCreating(function (EggCollection $collection) {
|
|
$chickens = Chicken::where('status', 'ACTIVE')
|
|
->inRandomOrder()
|
|
->take(20)
|
|
->get();
|
|
|
|
if ($chickens->isEmpty()) {
|
|
$chickens = Chicken::factory()->count(20)->create();
|
|
}
|
|
|
|
$itemCount = $this->faker->numberBetween(5, min(20, $chickens->count()));
|
|
$selectedChickens = $chickens->shuffle()->take($itemCount);
|
|
|
|
$totalEggs = 0;
|
|
|
|
foreach ($selectedChickens as $chicken) {
|
|
$eggsCount = $this->faker->numberBetween(0, 2);
|
|
|
|
if ($eggsCount <= 0) {
|
|
continue;
|
|
}
|
|
|
|
EggCollectionItem::create([
|
|
'egg_collection_id' => $collection->id,
|
|
'chicken_id' => $chicken->id,
|
|
'eggs_count' => $eggsCount,
|
|
]);
|
|
|
|
$totalEggs += $eggsCount;
|
|
}
|
|
|
|
$collection->update(['total_eggs' => $totalEggs]);
|
|
});
|
|
}
|
|
}
|