首页 文章

如何在Laravel 5.2中使用多对多的多态关系

提问于
浏览
8

我正在阅读laravel 5.2 docs以在我的Laravel应用程序中实现多对多的多态关系 . 我有许多模型,如 BlogQuestionPhoto 等,我想为所有这些模型设置标记系统 . 我用以下模式创建了Tag表

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

下面是数据透视表模式 . 数据透视表名称为 entity_tags

Schema::create('entity_tags', function (Blueprint $table) {
     $table->increments('id');
     $table->integer('tag_id')->unsigned();;
     $table->integer('taggable_id')->unsigned();
     $table->string('taggable_type');
     $table->timestamps();
     $table->index('tag_id');
     $table->index('taggable_id');
     $table->index('taggable_type');
});

这是 Tag 模型中为 Question 模型定义的关系

public function questions()
{
    return $this->belongsToMany('App\Question', 'entity_tags', 'tag_id', 'taggable_id');
}

并且 Question Model中定义了以下关系

public function tags()
{
    return $this->belongsToMany('App\Tag', 'entity_tags', 'taggable_id', 'tag_id');
}

现在我想定义Laravel 5.2中定义的Many to Many Polymorphic关系 .
我的问题是

  • 我如何定义它们?

  • 我应该删除多对多关系并且只定义多对多的多态关系吗?如果是,那么如何管理自定义数据透视表名称?

  • 是否需要使用单词 able 作为多态关系的一部分来后缀列名?

1 回答

  • 8
    • 使用return $ this-> morphToMany()而不是belongsToMany,并在Tag模型中,使用返回$ this-> morphedByMany()编写3个方法以获得反向关系 .

    • 您只需要多态定义,不需要多对多的正常定义 . 数据透视表的名称在默认约定的末尾带有'able',但您可以将其命名为任何所需名称 .

    • 不,你不必在最后有一个'able'的单词,它只是一种定义它更通用的方法,你可以命名它你想要的任何东西 .

    命名基于Laravel的一些默认约定 .

    更新:

    您有以下数据透视表模式:

    Schema::create('entity_tags', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('tag_id')->unsigned();;
            $table->integer('entity_id')->unsigned();
            $table->string('entity_type');
            $table->timestamps();
            $table->index('tag_id');
            $table->index('entity_id');
            $table->index('entity_type');
    });
    

    和标签表:

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

    因此,您希望为博客,视频和问题表/模型创建关系:

    Tag.php型号:

    public function questions()
    {
        return $this->morphedByMany('App\Question', 'entity', 'entity_tags');
    }
    
    public function blogs()
    {
        return $this->morphedByMany('App\Blog', 'entity', 'entity_tags');
    }
    
    public function videos()
    {
        return $this->morphedByMany('App\Video', 'entity', 'entity_tags');
    }
    

    Question.php / Blog.php / Video.php

    public function tags()
    {
        return $this->morphToMany('App\Tag', 'entity', 'entity_tags');
    }
    

相关问题