Below are the Tables with fiddle link
TableA
id | col1 | col2 |
---|---|---|
1 | 1 | 1 |
TableB
id | tableA_id | count |
---|---|---|
1 | 1 | 10 |
TableC
id | tableB_id | quantity |
---|---|---|
1 | 1 | 5 |
2 | 1 | 5 |
I have a three table with relation of each other.
TableA->TableB->TableC
->TableC
count
column in TableB->count is sum of TableC->quantity relation.
How Can I seed the tables using a Laravel Factory Faker?
What I have tried?
TableASeeder
Method:1
public function run()
$qty = fake()->randomElement([100, 150,200,250,300,400]);
$tbla = TableA::factory()->has(TableB::factory()->count(2)->state([
'count' => $qty,
])
->has(TableC::factory()->count(2)->state([
'quantity' => round($qty/2),
])))->create();}
Method:1 code I am getting below error message
Call to undefined method App\Models\TableB::tableb()
Method:2
public function run()
$event = TableA::factory()
->afterCreating(function ($tba) use($qty) {
TableB::factory()->for($tba)->state([
'count' => $qty,
])->afterCreating(function($tbb) use($qty){
TableC::factory()->for($tbb)->state([
'quantity' => round($qty/2),
])->count(2)->create();
})->count(2)->create();
})->create();
Method:2 code I am getting below error message
Call to undefined method 6Illuminate\Database\Eloquent\Relations\HasOne::getOwnerKeyName()
When I run the above seeder TableASeeder
it creates a TableA
Record and Two TableB
Records
Now I need to seed TableC
which is two records each with quantity sum equal to TableB->count
in the above case it should be 10.