加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 19:48:25 所属栏目:大数据 来源:网络整理
导读:我正在阅读laravel 5.2 docs以在我的Laravel应用程序中实现多对多的多态关系. 我有许多模型,如博客,问题,照片等,我想要所有的标签系统. 我用以下模式创建了Tag表 Schema::create('tags',function (Blueprint $table) { $table-increments('id'); $table-stri
我正在阅读laravel 5.2 docs以在我的Laravel应用程序中实现多对多的多态关系.
我有许多模型,如博客,问题,照片等,我想要所有的标签系统.
我用以下模式创建了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');
});

这是在问题模型的标签模型中定义的关系

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

并且在问题模型中定义了以下关系

public function tags()
{
    return $this->belongsToMany('AppTag','taggable_id','tag_id');
}

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

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

>使用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('AppQuestion','entity','entity_tags');
}

public function blogs()
{
    return $this->morphedByMany('AppBlog','entity_tags');
}

public function videos()
{
    return $this->morphedByMany('AppVideo','entity_tags');
}

Question.php / Blog.php / Video.php

public function tags()
{
    return $this->morphToMany('AppTag','entity_tags');
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读