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

时间:2016-02-28 20:03:59

标签: php laravel laravel-5.2

我正在阅读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模型

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

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

  • 我如何定义它们?
  • 我应该删除多对多 关系并且只定义多对多的多态关系? 如果是,那么如何管理自定义数据透视表名称?
  • 还需要使用作为其一部分的单词able作为后缀的列名称 多态关系?

1 个答案:

答案 0 :(得分:8)

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

  • 您只需要多态定义,不需要多对多的正常定义。数据透视表的名称是'能够'最后是默认约定,但您可以将其命名为任何名称。

  • 不,你不需要说“能够”这样的话。最后,它只是一种定义它更通用的方式,你可以将它命名为任何你想要的东西。

命名基于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');
}
相关问题