从用户到 Post 和类别的多态多对多

Polymorphic many to many from User to Post and Category

我需要实现像 Twitter 这样的关注系统,但除此之外,用户可以关注很多 Post 并且可以关注整个 Category 或者用户可以关注一个 User

我想出了这个关系。我正在使用 Laravel 5.1

用户模型

public function followers()
{
   return $this->belongsToMany('App\User', 'user_follows', 'user_id', 'follow_id');
}

public function follows()
{
   return $this->belongsToMany('App\User', 'user_follows', 'follow_id', 'user_id');
}

并关注类别

类别模型

public function followers()
{
   return $this->belongsToMany('App\User', 'category_follows', 'user_id', 'category_id');
}

和 Post 的方法相同,如您所见,我需要 3 个表 (user_follows, category_follows, post_follows) 才能完成这项工作。

我知道有 Polymorphic Relation 但我无法理解它。 请帮助我如何简化它。下面再次是要求

您可以使用 morphedByMany to create polymorphic many to many relations。您可以使用具有以下架构的单个 followables table,而不是单独的 *_follows table:

user_id           int      # user_id that is following something
followable_id     int      # id of the thing that is being followed
followable_type   string   # type of the thing that is being followed

这是一个示例实现:

类别,Post 和用户模型

/*
 * This function gets the followers of this entity. The
 * followable_id in the followables relation would be
 * the id of this entity. 
 */
function followers() {
    return $this->morphToMany('App\User', 'followable');
}

用户模型

/*
 * Gets the list of users that are followed by this user.
 */
function users() {
    return $this->morphedByMany('App\User', 'followable');
}

/*
 * Gets the list of posts that are followed by this user.
 */
function posts() {
    return $this->morphedByMany('App\User', 'followable');
}

/*
 * Gets the list of categories that are followed by this user.
 */
function categories() {
    return $this->morphedByMany('App\User', 'followable');
}

请注意,在这种情况下,一个 User 变形 多次,并且变形 多次,创建一个自我-引用多对多关系。

您创建的每个新 followable 实体,您都需要向该实体添加 followers() 函数,以及与 Users 对应的反向关系实体。您可以定义一个包含该函数的 Followable 特征,然后简单地将 use Followable; 添加到您添加的新实体中。