我正在尝试为这些任务中的任务和 NPC 建立一个多对多连接表...一个任务可以有多个 NPC,一个 NPC 可以用于多个任务。我正在使用 Laravel 5。
在为 Quest 表做种子时,我也在为连接表做种子,但出现以下错误:
Base table or view not found: 1146 Table 'clg_local.npc_quest' doesn't exist
创建 Quest 和 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');
}
对两种关系执行上述操作
在我看来,除非你需要一个不这样做的理由,否则请坚持惯例。
关于mysql - 找不到基表或 View : 1146 Table '' doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792656/