How to model Friendship relationships

时间秒杀一切 提交于 2019-11-30 23:54:37

You can use a table join (e.g. http://dev.mysql.com/doc/refman/5.0/en/join.html) to find all of the requests.

Actually you can use a subquery here:

SELECT * FROM users_status WHERE userid = "$userid" 
    OR userid in (SELECT request_to   FROM friendships where request_from = "$userid" AND friendship_status = 1)
    OR userid in (SELECT request_from FROM friendships where request_to   = "$userid" AND friendship_status = 1)

replace $userid with your user id

The simplest schema I can think of is:

PENDING_FRIENDSHIPS(request_from, request_to)
FRIENDSHIPS(request_from, request_to)

I also removed the ID because both fields on both tables will be compound primary keys (request_from, request_to).

To get all friends from the current user just run:

select * from friendships
where $currentUser = request_from OR $currentUser = request_to

This would return both columns and you would have to remove in PHP the current user.

Another way to get all friends from this schema is to run a UNION:

select request_from from friendships
where request_to = $currentUser
UNION
select request_to from friendships
where request_from = $currentUser

The drawback of this solution is that you're running 2 selects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!