Skip to content
Advertisement

Sequelize : How to query posts list from user id list?

To learn a little bit how a back end application works i’m currently creating a small instagram-like app using nodejs and sequelize (reactjs for the front).

I have 3 SQL tables :

Users id (pk) username email password

Posts id (pk) userId (fk) message mediaUrl

Following id (pk) userId (fk) followingId (fk)

I would like to know what is the cleanest way to retrieve posts from an array of followingId corresponding to a userId ?

Advertisement

Answer

I just found a way to achieve what i wanted :

const db = require("../models");
const User = db.users;
const Post = db.posts;
const Following = db.followers;
const Op = db.Sequelize.Op;

exports.requestPost = async (req, res) => {

  const followers = await Following.findAll({
    where: {
      userId: req.body.userId
    },
    attributes: [
      ['followingId', 'followingId']
    ]
  });

  const result = await followers.map(x => x.followingId);

  const posts = await Post.findAll({
    where: {
      userId: result
    }
  });
  return res.send(posts)
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement