首页 > 解决方案 > 在 laravel 中使用 morphTo() 多对多多态

问题描述

如何morphTo()在多对多关系中使用?

考虑一下我有这四个表:

Posts:
 - id
 - title

Videos:
 - id
 - title

Tags:
 - id
 - name

Taggable:
 - id
 - tag_id
 - taggable_type
 - taggable_id

在其他多态类型(如 one2one 或 one2many)中,我们可以轻松地在模型中$this->morhphTo()定义一个taggable()方法,该方法返回一个App\Postor的列表App\Video

class Tag extends Model
{
    public function taggable()
    {
        return $this->morphTo();
    }
}
// So when we call taggable(), it returns either App\Post or App\Video
// But what about using this way in many to many polymorphic relations?


我想要在我的App\Tag模型中有这样的东西。这可能吗?

到目前为止,这个问题已经花了我 8 天的时间,我仍然不知道。

标签: phplaraveleloquentpolymorphic-relationship

解决方案


推荐阅读