user3871
user3871

Reputation: 12664

Seeding one to many relationship

I am creating the API (Laravel 5) for an RPG game, and am trying to seed data.

Each level contains many quests, and each quest belongs to one level.

Looking through the Laravel docs, I only see relationships for inserting related model data for one:one (associate), and many:many (sync, attach), but nothing for the example of one:many (level has many quests, but quests only have one level).

You can see below in the seeding that I am trying to randomly associate multiple quests to levels. I've also tried attach and sync but get the errors

Call to undefined method Illuminate\Database\Query\Builder::associate()

and

Call to undefined method Illuminate\Database\Query\Builder::attach()

Level model:

public function quests()
{
    return $this->hasMany(Quest::class);
}

Quest model:

public function levels()
{
    return $this->belongsTo(Level::class);
}

Level Seeder:

public function run()
{
    Eloquent::unguard();

    $levels = $this->createLevels();

    $quests = Quest::all()->toArray();

    /*
     * Randomly join level id with associated quest ids
     */
    foreach ($levels as $level) {

        $level->quests()->associate($quests[rand(0, count($quests) - 1)]['id']);
    }

Upvotes: 2

Views: 2507

Answers (2)

Almazik G
Almazik G

Reputation: 1077

You may use save() method, as stated by @Mithredate.

foreach ($levels as $level) {
    $quest->levels()->save($level);
}

Upvotes: 4

Mehrdad Hedayati
Mehrdad Hedayati

Reputation: 1454

Use eloquent save() method. You can find the documentations here

Upvotes: 1

Related Questions