Why filling factory with parent_id pointing to other items always null?

74 Views Asked by At

Making seeder with dummy data on laravel 10 site I need to make some items with parent_id pointing to other items

<?php

use App\Models\Item;
use App\Models\User;

public function definition()
{
    $items = Item::all();
    $parent_id = null;
    if (count($items) > 0) {
        if (rand(1, 3) >= 2) {
            $parent_id = $this->faker->randomElement($items)['id'];
        }
    }

    ...
    return [
        'parent_id' => $parent_id,
        'user_id' => $this->faker->randomElement(User::all())['id'],

But in all items rows parent_id has null, looks like code

$items = Item::all();

is run only once...

How can I fix it ?

EDDITIVE CODE :

This seeder was calling from ItemSeeder.php file

Item::factory()->count(20)->create();

And ItemSeeder.php is called from database/seeders/DatabaseSeeder.php file, which is run once, during initial migration...

Thanks in advance!

1

There are 1 best solutions below

2
On BEST ANSWER

you can use factory callbacks if you have not tried it.

public function configure()
{
    return $this->afterCreating(function (Item $item) {
        $items = Item::all();

        if ($items->count() > 0 && rand(1, 3) >= 2) {
            $parent = $items->random();
            $item->update(['parent_id' => $parent->id]);
        }
    });
}