Mahir Altınkaya
Mahir Altınkaya

Reputation: 439

Sequelize INNER JOIN

I need to Inner Join with sequelize. I tried something but i cant understand it.Anyone help me for this ;

I have two model that are Users and Payments. I want to get Users with payments data.

I shared basicaly Example below Anyone explain for me ? and how can i make it ?

Totaly need ' SELECT * FROM Users INNER JOIN Payments ON Users.id=Payments.user_id WHERE Users.email=?';

Users.findOne({
where:{
user_email:payload.email
},
include:[{
model:Payments,
where:['Payments.user_id = Users.id']
}]
})

enter image description here

Update: Added this. After gived Error: Include unexpected. Element has to be either a Model, an Association or an object.

  Users.hasMany(Payments, { foreignKey: "user_id" });
  Payments.belongsTo(Users, { foreignKey: "id" });

Upvotes: 2

Views: 5980

Answers (1)

Rifat Bin Reza
Rifat Bin Reza

Reputation: 2761

On your relation you can make it required for inner join.

Users.findOne({
    where: {
        user_email: payload.email
    },
    include: [{
        model: Payments,
        where: ['Payments.user_id = Users.id'],
        required: true
    }]
})

Upvotes: 6

Related Questions