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

How to use many to many polymorphic relation in Laravel 5.2

我正在阅读 laravel 5.2 文档以在我的 Laravel 应用程序中实现多对多多态关系。 我有许多模型,如 BlogQuestionPhoto 等,我想为所有模型安装标记系统。 我使用以下架构

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

下面是枢轴 table 架构。枢轴 table 名称是 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模型

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

现在我想定义Laravel 5.2中定义的多对多多态关系。
我的问题是

  • 使用return$this->morphedByMany()代替belongsToMany,在Tag模型中,用return$this->morphedByMany()写3个方法用于反向关系。

  • 你只需要多态定义,不需要多对多的普通定义。根据默认约定,枢轴的名称 table 以 'able' 结尾,但您可以随意命名。

  • 不,你不必在最后有一个词'able',它只是一种定义它更笼统的东西的方式,你可以给它起任何你想要的名字.

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

更新:

您有以下枢轴 table 架构:

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');
});

和标签 table:

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

所以您想为博客、视频和问题创建关系 tables / models:

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');
}