coderunner
coderunner

Reputation: 935

Implementing a "Follow" user feature using PHP and Mysql

Issue: I am working on a kind of e-commerce platform which has sellers and buyers.Now in my case a seller can also be a buyer i.e every user can buy plus sell.
So i have a single table called users.Now I want to implement a follow vendor/user feature,wherein the user can click follow and he sees all the goods listed by that vendor under his account(till he unfollows).

Now my traditional approach was to have a table that has a key and two columns to store the follower and the followed Eg: |id | userId| vendorId
So it will go horizontally as the users go on following others.But if I have a user following many people(say 100) my query may take a lot of time to select a 100 records for each user.

Question: How can I implement the follow mechanism?Is there a better approach than this?I am using PHP and Mysql.

Reasearch: I tried going through how facebook and Pinterest handle it,but that seemed a bit too bigg for me to learn now as I don't expect as many users immedeately. Do I need to use memcache to enhance the performance and avoid recurring queries?Can I use a Document Database in any sense parallel with Mysql?

I would like a simple yet powerful implementation that would scale if my userbase grows gradually to a few thousands.

Any help or insights would be very helpful.

Upvotes: 0

Views: 1221

Answers (2)

Jakub Kania
Jakub Kania

Reputation: 16487

The junction table is probably the best approach but still a lot depends on your clustered index.

  • Table clustered with a key on the substitute key id can make adding new records a bit faster.

  • Table clusetered with a key (userId,vendorId) will make the queries where you look for vendors a certain user follows faster

  • Table clustered with a key (vendorId,userId) will make the queries where you look for users that follow a certain vendor faster

Upvotes: 2

Pudge601
Pudge601

Reputation: 2068

Since, from my understanding of this scenario, a user may follow many vendors, and a vendor may have many followers, this constitutes a many<->many relationship, and thus the only normalised way to achieve this in a database schema should be through using a link table, exactly as you described.

As for the performance considerations, I wouldn't worry too much about it, since it could be indexed on userId and vendorId, the queries should be fine.

Upvotes: 4

Related Questions