Skip to content
Advertisement

Need to fetch all users that logged in user is following as an objects

I am building handmade MVC framework, and I want to implement following system (Like Twitter) so User that is signed in can follow another user and when that signed in user visits his profile he can see all other users that he is following and vice versa. I am not sure which query to apply in order to fetch all the users that current logged in user is following. I tried couple of sql queries in order to fetch those followers as an objects but failed. Further you have tables users and follows and their explanation.

This is users table.

enter image description here

This is follows table which has composite primary key (user_id,following_user_id) and they are both foreign keys that are pointing to column id from table users

enter image description here

Here is some data from follows table

enter image description here

I’ve tried this but it is fetching every user (as an array)

SELECT users.id,users.username FROM follows INNER JOIN users ON follows.user_id = users.id;

Advertisement

Answer

Assuming that you have these two tables:

CREATE TABLE `user`
(
    `user_id` int AUTO_INCREMENT,
    `name` varChar(255),
    PRIMARY KEY (`user_id`)
);

CREATE table `user_following`
(
    `user_id` int,
    `following_user_id` int,
    PRIMARY KEY (`user_id`, `following_user_id`),
    CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`),
    CONSTRAINT FOREIGN KEY (`following_user_id`) REFERENCES `user` (`user_id`)
);

With these values:

INSERT INTO `user` VALUES (1, 'Alice');
INSERT INTO `user` VALUES (2, 'Bob');
INSERT INTO `user` VALUES (3, 'Charlie');

INSERT INTO `user_following` VALUES (1, 2);

You can find all of the users that “Alice” (user id=1) follows by running:

SELECT
    *
FROM
    `user`
WHERE
    `user_id`
    IN
    (SELECT `following_user_id` FROM `user_following` WHERE `user_id` = 1);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement