A. Atiyah
A. Atiyah

Reputation: 555

many-to-many relationships in sequelize can't use include?

So I have a project in which a User can join a Weekly Ladder so I made a belongsToMany relationship between both fields through a third model called UserLadder where I also added an extra field that keeps track of the user points at this ladder.

Basically now in my express app I need a route to shop users and their points by tournament so I wrote this:

 const leaderboard = await UserLadder.findAll({
   where: {
     weeklyLadderId: req.params.id,
   },
   limit: req.params.playersNumber,
   order: [['userPoints', 'DESC']],
 });

 res.json(leaderboard);

and it worked in the sense of it did show me everyone in this tournament and ordered them according to their points but problem was that the user showed just as a userId field and I wanted to eager load that using Include but it says that there's no relation between the user model and the userladder model.

the temporary solution I did was:

const ladder = await WeeklyLadder.findByPk(req.params.id);
const users = await ladder.getUsers({
  attributes: ['displayName'],
});
res.json(users);

which I got the tournament by Id and then got there users of the tournament but this is a 2 step process and I know there's a way to do it through the third UserLadder model I just cant figure it out

any ideas?

accosiations:

const User = require('./models/User');
const WeeklyLadder = require('./models/WeeklyLadder');
const Game = require('./models/Game');
const UserLadder = require('./models/UserLadder');

User.belongsToMany(WeeklyLadder, {
  through: UserLadder,
});

WeeklyLadder.belongsToMany(User, {
  through: UserLadder,
});

Game.hasMany(WeeklyLadder);

WeeklyLadder.belongsTo(Game);

enter image description here

Upvotes: 0

Views: 89

Answers (1)

You can execute with just one request :

db.User.findOne({
    include: [
        {
            model: db.WeeklyLadder,
            as: "WeeklyLadder",
            where: {
                title: "tournament 1", // where on WeeklyLadder
            },
        },
    ],
})

On your models :

User.associate = (models) => {
    models.User.belongsToMany(models.WeeklyLadder, {
        as: "WeeklyLadder",
        through: "UserWeeklyLadder",
        foreignKey: "fk_user_id",
        otherKey: "fk_weekly_ladder_id",
    })
}

...

WeeklyLadder.associate = (models) => {
    models.WeeklyLadder.belongsToMany(models.User, {
        as: "User",
        through: "UserWeeklyLadder",
        foreignKey: "fk_weekly_ladder_id",
        otherKey: "fk_user_id",
    })
}

Upvotes: 1

Related Questions