未找到基础表或视图:1146表''不存在
问题描述:
我试图在这些任务中种下多对多任务和npcs连接表...任务可以有许多npcs, NPC可以用于许多任务。我使用Laravel 5.未找到基础表或视图:1146表''不存在
当无欲无求的任务表,我也无欲无求的连接表,但我得到以下错误:
Base table or view not found: 1146 Table 'clg_local.npc_quest' doesn't exist
创建任务和Quest_NPC表:
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();
});
在一个单独的创建,指定我的关系:
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');
});
很明显我创建了一个quest_npc
表,但它正在寻找一个npc_quest
表?
任务播种机:
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模型:
public function npcs()
{
return $this->belongsToMany(Npc::class);
}
任务模式:
public function quests()
{
return $this->belongsToMany(Quest::class);
}
答
从文档,Laravel '假定' 表名是
derived from the alphabetical order of the related model names
所以在你的情况下,这就是“为什么”。
您可以将第二个参数添加到您的belongsToMany
调用中,以指示您想要使用的名称。例如:
public function quests()
{
return $this->belongsToMany(Quest::class, 'quest_npc');
}
做好了以上两种关系
在我看来,坚持公约,除非你需要一个理由不这样做。
你能否定义“坚持约定”的含义? – Growler
我的意思是按字母顺序命名你的牌桌。所以在这种情况下'npc_quest'。有时候这是不可能的 - 例如,您可能正在将旧的数据库或应用程序迁移到laravel。但是如果你从头开始,坚持公约 – Chris