未找到基础 table 或视图:1146 Table '' 不存在

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

我正在尝试为任务和这些任务中的 NPC 设置多对多连接 table...一个任务可以有多个 NPC,一个 NPC 可以用于多个任务。我正在使用 Laravel 5.

为任务 table 播种时,我也在为加入播种 table,但出现以下错误:

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

创建任务并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();

    });

在单独的创建中,我指定了我的关系:

    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 table,但它正在寻找 npc_quest table?

任务播种机:

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 'assumes' table 名称为

derived from the alphabetical order of the related model names

所以在你的情况下,就是 "why"。

您可以在 belongsToMany 调用中添加第二个参数,以指明您要使用的名称。例如:

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

对两个关系执行上述操作

在我看来,坚持惯例,除非你需要一个不这样做的理由。