How to model Friendship relationships

2019-02-15 08:42发布

问题:

I have been trying to figure out how to do this, and even with looking at other examples, I can't get it figured out, so maybe I can get some personalized help.

I've got two tables, users_status and friendships.

In the users_status table I have a field userid, and several others. In the friendships table, I have the fields request_to,request_from, and friendship_status.

Basically what I want to do is get all of the status posts by the current user AND those who are friends of the current user (which I can specify in my PHP using a $userid variable).

Here's an example of the friendships table structure. When a friend request is sent, the userid of the sender and receiver are placed in the table, with a friendship_status of 0. When the request is accepted, the friendship_status is set to 1 and those two are now friends.

friendship_id   request_from    request_to  friendship_status
1               111248          111249      1
2               111209          111249      1
3               111209          111248      0
11              111209          111259      1
5               111252          111209      1
12              111261          111209      1

I realize this may not even be the best structure for determining friendships, especially since the site is relationship based and having to check for friendship connections will be a frequently used thing.

Would it perhaps be better to have two separate tables for friend_requests and friendships? If so, how would I structure/manage the friendships table?

回答1:

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



回答2:

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