Growler Growler - 1 month ago 7
MySQL Question

Base table or view not found: 1146 Table '' doesn't exist

I am trying to seed a many-to-many join table of quests and npcs in those quests... a quest can have many npcs, and an NPC can be used in many quests. I am using Laravel 5.

enter image description here

When seeding the Quest table, I'm also seeding the join table, but am getting the following error:


Base table or view not found: 1146 Table 'clg_local.npc_quest' doesn't exist


Create Quest and 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 a separate create, I specify my 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 I am creating a
quest_npc
table, but it's looking for a
npc_quest
table?

Quest seeder:

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

$quests = $this->createQuests();

$npcs = Npc::all()->toArray();

foreach ($quests as $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);
}

Answer

From the documentation, Laravel 'assumes' the table name to be

derived from the alphabetical order of the related model names

So in your case, that's the "why".

You can add a second parameter to your belongsToMany call to indicate the name you would like to use. For example:

public function quests()
{
    return $this->belongsToMany(Quest::class, 'quest_npc');
}

Do the above for both relationships

In my opinion, stick to the convention, unless you need a reason not to.