我正在创建一个涉及可以成为朋友的用户的数据库架构,我想知道为这些朋友建立友谊的最佳方式是什么。它应该是自己的表,只有两列,每列代表一个用户?谢谢!
答案 0 :(得分:48)
create table
friendship(
user bigint,
friend bigint,
primary key(user, friend),
key(friend, user),
constraint `fk_user` foreign key (user) references user(id),
constraint `fk_friend` foreign key (friend) references user(id)
);
当用户1向用户2发送友情请求时,请执行
insert into friendship (user, friend) values (1,2);
如果用户2拒绝该请求,
delete from friendship where user = 1 and friend = 2;
如果用户2接受它:
insert into friendship (user, friend) values (2,1);
然后,可以通过这种方式找到友谊:
select f1.*
from friendship f1
inner join friendship f2 on f1.user = f2.friend and f1.friend = f2.user;
您可以使用此最后一个查询制作视图,它可以帮助您查询用户的朋友,甚至是朋友的朋友。
答案 1 :(得分:4)
我不确定,这是我想要对整个设置进行建模的方式。当用户A向用户B发送请求时,在我看来,创建了pending_friendship。 当用户B接受该请求时,建立两者之间的友谊。通常这将是一种双向关系,并且会很棒。但我希望确保将来有单向关系的余地。因此,我将通过使用两个关系表和一个用户自己的表来为场景建模。
用户( 用户身份, 电子邮件, password_hash, 名称, ... ... )
pending_friendship( user_id_from, user_id_to )
友谊( friendship_id, current_user_id, friend_user_id, is_following boolean#这将确保单向关系的范围。 )
现在让我们查看用例 -
1- 用户A向用户B发送请求 - 我会在pending_friendship表中创建一个条目。
当用户B想要查看哪些朋友请求待处理时,我们可以根据friend_request_to列进行选择查询。
2- 用户B接受好友请求 - pending_friendship项目将从表格中删除。在友谊表中为两边关系制作了两个条目。两个用户都会互相关注。
3- 用户B是朋友,不想关注用户A的Feed 对于用户B的用户A的友谊行,is_following列设置为false。
4- 用户A不想成为B的朋友 - (毕竟B在案例3中取消了他:-))我们继续删除两行之间的友谊两个用户。
此架构确实具有更多复杂性,但增加了更多清晰度。它还允许您关注用户。
答案 2 :(得分:0)
是(使用n:m链接表)。
您有两个实体:
分别创建一个表。