cyonder
cyonder

Reputation: 872

How to implement Friendship Structure in a website

I have developed a friendship system, where users table have a friendship column. In this column, I store user's id in an array by separating with a coma. Example: 1,5,15,20

So it means, user is friend with other users, who has 1,5,15,20 as id. But there is another way to do this. Creating a friendship table and store everything there. Like in this examples:

https://stackoverflow.com/questions/25101089/mutual-friendship-rails-4

How to Implement a Friendship Model in Rails 3 for a Social Networking Application?

My question is which way is the best way as efficiency and speed? Using an array column or separate table?

Thank you.

Upvotes: 4

Views: 187

Answers (1)

Martin Schmidt
Martin Schmidt

Reputation: 309

Efficiency and speed depend on the way you use this data.

1# You have a model User and a column 'friends' with user_ids of friends in the same table.

This is fast to read and needs not much storage space. But you have to decide in whose table row the data should be stored, because you absolutely don't want to store/manage the same data in two different table rows. If you just need a method like User.friends this is a fast and efficient way to store the ids. But if you would like to have a methods like User.is_friends_with you have to query every row in your user table. That wouldn't be neither fast nor efficient.

2# You have a model User and a column 'is_friends_with' with user_ids of friends in the same table.

Same as #1, but User.is_friends_with would be fast and User.friends would query all rows in the table.

3# You have a model User and a model Friendship

This is fast and efficient if you want to query friendships in both directions. It's also possible to extend the Friendship model to store some other data with it (e.g. since when the users are friends or where they know each other from). But if a user has 100 friends you need 100 rows your friendships table.

If you don't know yet what to do with all the friendships, you should go with #3. It's the most flexible way to do it and it's easy to extend later on.

Upvotes: 1

Related Questions