mysql - 找不到基表或 View : 1146 Table '' doesn't exist

标签 mysql database laravel laravel-5 seed

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

enter image description here

在为 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/

相关文章:

mysql - 使用不同的条件连接同一个表上的不同行

php - 除了随机 ID 检索之外,在表中存储数据的最简单数据库解决方案是什么?

php - Laravel 中如何检查模型对象是否为空?

ruby - 如何在 ruby​​ 中使用 ssh 隧道连接 postgres 数据库

mysql - 在mysql中使用Alter和ignore删除重复项

php - laravel 会自动添加分组依据吗? Laravel toSql 与正在运行的查询的奇怪行为。

php - Laravel Eloquent 多表

php - CakePHP 3.0 连接数据库失败

php - 通过 PHP 将 MySql 中的项目插入到 HTML Bootstrap 页面

mysql - 我可以将 MySQL 添加到已有 Node.js 的 EC2 实例上吗?