从用户到帖子和类别的多态多对多 [英] Polymorphic many to many from User to Post and Category
问题描述
我需要实现一个Twitter之类的关注系统,但除了一个用户之外,用户可以关注许多Post
并且可以关注整个Category
,或者用户可以关注User
.
I need to implement a follow system like twitter but with exception a user can follow many Post
and can follow whole Category
or a user can follow a User
.
我想出了这种关系.我正在使用Laravel 5.1
I have come up with this relationship. I am using 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)
才能完成这项工作.
and for Post is the same way, as you can see I need 3 tables (user_follows, category_follows, post_follows)
to make this work.
我知道有Polymorphic Relation
,但是我不能把头缠在它上面.
请帮助我如何简化它.下面再次是要求
I know there is Polymorphic Relation
but I cant wrap my head around it.
Please help how i can simplify it. once again below are the requirements
- 用户可以关注许多帖子
- 用户可以遵循许多类别
- 用户可以关注许多用户
- User can follow many Posts
- User can follow many Category
- User can follow many User
推荐答案
You can use morphedByMany
to create polymorphic many to many relations. Instead of having separate *_follows
tables, you can have a single followables
table with the following schema:
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');
}
请注意,在这种情况下,User
会同时被变体和变体变为,从而创建了一个自引用的多对多关系.
Note that in this case, a User
is both morphed by many and morphed to many, creating a self-reference many to many relationship.
您创建的每个新的 followable 实体,都需要向该实体添加followers()
函数,并与Users
实体对应的逆关系.您可以定义一个包含该函数的Followable
特征,只需将use Followable;
添加到您添加的新实体中即可.
Every new followable entity you create, you will need to add the followers()
function to that entity, and a corresponding inverse relation to the Users
entity. You could define a Followable
trait containing that function, and simply add use Followable;
to the new entity you add.
这篇关于从用户到帖子和类别的多态多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!