1

I have a table clients and a table contracts. In my Client model I have

public function contract()
    {
        return $this->hasOne(
            'App\Models\Contract',
            'client_id',
            'id'
        );
    }

I don't want to have any client without a contract in my database. When I seed my clients, using the factory with faker data, I want to create contracts that are mapped to client using the foreign key user_id on the contract.

PeterPan
  • 195
  • 2
  • 16
  • https://stackoverflow.com/a/44462235/9636400 – geertjanknapen May 05 '22 at 12:02
  • Yes it does, thank you. In my case it is `save()` instead of `saveMany()`, but I already tested it and it is working. Quick question to learn to avoid asking duplicate questions in the future, because I searched a solution before I asked. Did I need to know that this is called "Seeding Relationships"? – PeterPan May 05 '22 at 12:07
  • Would help for being more specific in searches. Is it a must? No. probably not. – geertjanknapen May 05 '22 at 12:09

2 Answers2

1

make sure to make a factory for each table and then you can simply do something like

        Client::factory()
        ->count(3)
        ->has(Contract::factory()->forUser()->create())
        ->create();

Notice: check your relations in your models then it should be fine :)

Vahid Marali
  • 136
  • 6
0

This is what worked for me:

App\Models\Client::factory(10)->create()->each(function ($client) {
    $client->contract()->save(Contract::factory()->make());
});
PeterPan
  • 195
  • 2
  • 16