从用户到帖子和类别的多种多样性

时间:2015-11-13 12:17:09

标签: php many-to-many relationship laravel-5.1 polymorphic-associations

我需要实施像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但我无法绕过它。 请帮助我如何简化它。再次以下是要求

  • 用户可以关注多个帖子
  • 用户可以使用多个类别
  • 用户可以关注多个用户

1 个答案:

答案 0 :(得分:2)

您可以使用morphedByMany to create polymorphic many to many relations。您可以拥有一个包含以下模式的<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <div id="search-container" class="inner-addon right-addon"> <input id="pac-input" class="controls" type="text" placeholder="Enter a location"> <span id="searchclear" class="glyphicon glyphicon-remove-circle" onclick="clearAllSearch()"></span> </div> <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>表,而不是使用单独的*_follows表。

followables

以下是一个示例实现:

类别,帖子和用户模型

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

用户模型

/*
 * 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'); } 的变形变为很多,并且变形变为很多,从而创建了多对多关系的自引用。 / p>

您创建的每个新可跟随的实体,您需要将User函数添加到该实体,并与followers()实体相对应的反向关系。您可以定义包含该功能的Users特征,只需将Followable添加到您添加的新实体中。