4

I have one speciality that can have many procedures.

I am wanting to seed both the speciality with many procedures.

Models:

Speciality

class Speciality extends Model
{

    protected $fillable = ['name'];

    public function procedures() {
        return $this->hasMany('App\Procedure');
    }
}

Procedure

class Procedure extends Model
{
    protected $fillable = ['speciality_id', 'name'];

    public function speciality() {
        return $this->belongsTo('App\Speciality');
    }
}

Factories:

Speciality

$factory->define(App\Speciality::class, function (Faker $faker) {
    return [
        'name' => 'Example'
    ];
});

Procedure

$factory->define(App\Procedure::class, function (Faker $faker) {
    return [
        'name' => $faker->realText(20)
    ];
});

Seeding:

public function run()
    {
        factory(App\Speciality::class)->create()
            ->each(function($speciality) {
                $speciality->procedures()
                    ->saveMany(factory(App\Procedure::class, rand(5,20))
                    ->make()
                );
        });
    }

The error shown is:

SQLSTATE[HY000]: General error: 1364 Field 'speciality_id' doesn't have a default value (SQL: insert into procedures (name, updated_at, created_at) values (It means much the., 2018-04-17 19:09:31, 2018-04-17 19:09:31))

speciality_id isn't set as a value within the procedure factory, because it's the foreign key to the speciality. But my understanding of using $speciality->procedures() is it would automatically assign the speciality_id upon seeding.

Why is this error happening please. Many thanks.

1 Answers1

0

I may be wrong here but I think there is just a small issue of when you call make:

public function run()
    {
        factory(App\Speciality::class)->create()
            ->each(function($speciality) {
                $speciality->procedures()
                    ->saveMany(factory(App\Procedure::class, rand(5,20))->make());     

        });
    }

Never used this with saveMany() before though, only save(), but try it out?

Josh Rumbut
  • 2,640
  • 2
  • 32
  • 43