Q:

Sequelize two relationships of the same class

Hello I have a question about sequelize
I have two entities two models
users
and match
a match has two users
my doubt how I would make this relationship
I would have to for two user_id?
my match would basically have
match id, player id one, player id two
I doubt how to relate or define this in sequelize

A:

You can define match as following. I assume you have UserModel.id as Seqeulize.INTEGER.
const MatchModel = Sequelize.define("Match", {
    // ... Other column declaration

    // Two user column -- which are not linked yet.
    playerOneId: {
        type: Sequelize.INTEGER,
        allowNull: false
    },
    playerTwoId: {
        type: Sequelize.INTEGER,
        allowNull: false
    }
})

// Now time to link the UserModel
// I assume you have `UserModel` declared before doing this.
MatchModel.belongsTo(UserModel, {
    foreignKey: {
        name: "playerOneId"
    },
    as: "playerOne"
}

MatchModel.belongsTo(UserModel, {
    foreignKey: {
        name: "playerTwoId"
    },
    as: "playerTwo"
}

Now while query a MatchModel do following
MatchModel.findOne({
    where: {
         // Your condition goes here
    },
    includes: [
        {
             model: UserModel,
             as: "playerOne"
        },
        {
             model: UserModel,
             as: "playerTwo"
        },
    ]
})

