i trying seed many-to-many join table of quests , npcs in quests... quest can have many npcs, , npc can used in many quests. using laravel 5.
when seeding quest table, i'm seeding join table, getting following error:
base table or view not found: 1146 table 'clg_local.npc_quest' doesn't exist
create quest , quest_npc table:
public function up() { /* * create quests table */ schema::create('quests', function(blueprint $table) { $table->increments('id'); $table->string('quest_name')->nullable(); $table->unsignedinteger('reward_xp')->nullable(); $table->string('reward_items')->nullable(); $table->unsignedinteger('reward_money')->nullable(); }); /* * create quests_npcs join table */ schema::create('quest_npc', function(blueprint $table) { $table->increments('id'); $table->unsignedinteger('quest_id')->nullable(); $table->unsignedinteger('npc_id')->nullable(); });
in separate create, specify relations:
schema::table('quest_npc', function(blueprint $table) { $table->foreign('quest_id')->references('id')->on('quests')->ondelete('cascade'); $table->foreign('npc_id')->references('id')->on('npcs')->ondelete('cascade'); });
clearly creating quest_npc
table, it's looking npc_quest
table?
quest seeder:
public function run() { eloquent::unguard(); $quests = $this->createquests(); $npcs = npc::all()->toarray(); foreach ($quests $quest) { $quest->npcs()->attach($npcs[rand(0, count($npcs) - 1)]['id']); } private function createquests() { quest::unguard(); $quests = []; foreach ( [ [ 'quest_name' => 'quest 1', 'reward_xp' => 200, 'reward_items' => null, 'reward_money' => 200, ], ...
npc model:
public function npcs() { return $this->belongstomany(npc::class); }
quest model:
public function quests() { return $this->belongstomany(quest::class); }
from documentation, laravel 'assumes' table name
derived alphabetical order of related model names
so in case, that's "why".
you can add second parameter belongstomany
call indicate name use. example:
public function quests() { return $this->belongstomany(quest::class, 'quest_npc'); }
do above both relationships
in opinion, stick convention, unless need reason not to.
Comments
Post a Comment