【问题标题】:Base table or view not found: 1146 Table '' doesn't exist未找到基表或视图:1146 表 '' 不存在
【发布时间】:2015-12-23 21:42:33
【问题描述】:

我正在尝试在这些任务中播种任务和 NPC 的多对多连接表……一个任务可以有多个 NPC,一个 NPC 可以用于许多任务。我正在使用 Laravel 5。

在播种 Quest 表时,我也在播种连接表,但出现以下错误:

未找到基表或视图:1146 表 'clg_local.npc_quest' 不存在

创建 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);
}

【问题讨论】:

    标签: mysql database laravel laravel-5 seed


    【解决方案1】:

    从文档中,Laravel '假定'表名是

    源自相关型号名称的字母顺序

    所以在你的情况下,这就是“为什么”。

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

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

    对两种关系都执行上述操作

    在我看来,请遵守约定,除非您需要理由不这样做。

    【讨论】:

    • 你能定义你所说的“遵守约定”吗?
    • 我的意思是按字母顺序命名您的表格。所以在这种情况下'npc_quest'。有时这是不可能的——例如,您可能正在将旧数据库或应用程序迁移到 laravel。但如果你是从头开始,请遵守约定
    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 2020-07-20
    • 2017-07-22
    • 2018-10-17
    • 1970-01-01
    • 2014-10-08
    • 2019-01-28
    • 2017-08-02
    相关资源
    最近更新 更多