首页 > 解决方案 > 未找到 morphToMany 列

问题描述

我遵循 laravel 文档中的教程,但似乎教程没有完整解释参数 morphToMany 以明确确定函数应该指向什么。

SQLSTATE [42S22]:未找到列:1054 '字段列表'中的未知列'tagables.tagables_id'(SQL:选择. tags* tagables,. tagables_idas pivot_tagables_id, .as , .as from inner join on . = . where . = 1 and . = 应用\模型\漫画)tagablestag_tag_idpivot_tag_tag_idtagablestagables_typepivot_tagables_typetagstagablestagstag_idtagablestag_tag_idtagablestagables_idtagablestagables_type

媒体表

    Schema::create('media', function (Blueprint $table) {
         $table->mediumIncrements('media_id)->nullable(false);
         $table->string('title', 255);
    });

标签表//标签内的一行(步行)

    Schema::create('tags', function (Blueprint $table) {
        $table->mediumIncrements('tag_id');
        $table->string('tag_name', 255);
    });
   

可标记表

    Schema::create('tagables', function (Blueprint $table) {
        $table->unsignedMediumInteger('tag_id')->nullable(false);
        $table->unsignedMediumInteger('tagable_id')->nullable(false);
        $table->string('tagable_type', 255)->nullable(false);
    });

漫画模型

public function tags()
{
    return $this->morphToMany(Tag::class, 'tagable');
}

漫画控制器

   // insert new comic
    $comic = Comic::create([
        'title'         => 'Doraemon',
    ]);
   
   // Insert into tagables table with current comic id and bind to tag id 1 
   which is walking

   $comic->tags->create([
       'tag_id' => 1
   ]);

它成功插入到媒体中,但未能插入到 tagables 表中。

标签: laravel

解决方案


我在您的代码中发现了一些错误。请尝试重写此代码。您的代码有一个工作示例。我已经为你检查过了

2021_04_10_073813_create_media_table.php

 Schema::create('media', function (Blueprint $table) {
        $table->id();
        $table->string('name', 255);
        $table->timestamps();
    });

2021_04_10_073837_create_tags_table.php

 Schema::create('tags', function (Blueprint $table) {
        $table->id();
        $table->string('name', 255);
        $table->timestamps();
    });

2021_04_10_073856_create_taggables_table.php

Schema::create('taggables', function (Blueprint $table) {
        $table->id();
        $table->unsignedMediumInteger('tag_id')->nullable(false);
        $table->unsignedMediumInteger('taggable_id')->nullable(false);
        $table->string('taggable_type');
        $table->timestamps();
    });

class Media extends Model
{
    protected $guarded = [];

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

class Tag extends Model
{
    protected $guarded = [];

    public function medias()
    {
        return $this->morphedByMany(Media::class, 'taggable');
    }
}

最后在一些控制器中

$media = Media::create([
            'name'         => 'media name1',
        ]);

        $tag = $media->tags()->create([
            'name' => 'tag name1',

        ]);

推荐阅读