php - Seeding one to many relationship -


i creating api (laravel 5) rpg game, , trying seed data.

each level contains many quests, , each quest belongs 1 level.

looking through laravel docs, see relationships inserting related model data one:one (associate), , many:many (sync, attach), nothing example of one:many (level has many quests, quests have 1 level).

you can see below in seeding trying randomly associate multiple quests levels. i've tried attach , sync errors

call undefined method illuminate\database\query\builder::associate()

and

call 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 associated quest ids      */     foreach ($levels $level) {          $level->quests()->associate($quests[rand(0, count($quests) - 1)]['id']);     } 

you may use save() method, stated @mithredate.

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

Comments