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
)