Here is the table stucture
- Table A
- Table B has foreign key a_id
- Table C has foreign key a_id and b_id
I am trying to Seed these three tables with Eloquent Relationships
Here is my code structure
class A extends Model
{
use HasFactory;
protected $fillable = [...];
public function b()
{
return $this->hasMany(B::class);
}
public function c()
{
return $this->hasMany(C::class);
}
}
class B extends Model
{
use HasFactory;
protected $fillable = [...];
public function c()
{
return $this->hasMany(C::class);
}
}
class C extends Model
{
use HasFactory;
protected $fillable = [...];
}
class DatabaseSeeder extends Seeder
{
public function run()
{
\App\Models\A::factory(5)
->has(\App\Models\B::factory(2))
->has(\App\Models\C::factory(1))
->create();
}
}
Error:
SQLSTATE[HY000]: General error: 1364 Field 'b_id' doesn't have a default value (SQL: insert into
c(...a_id,updated_at,created_at)
Your seeder will create 5
Amodels.For each of these 5
A, it's going to try and do two thingsB, passing ina_id.C, passing ina_id, but not passing anyb_id.Here's how each of those
Amodels would look like.To fix it you will need to either remove
has(\App\Models\C::class)or make aBmodel to associate with it.You need to define the
belongsTorelationship for this to work.For example
You could also not create everything in one statement.