luis
luis

Reputation: 202

sequelize: join three tables

Consider these tables

const User = sequelize.define('users', {
  name: {
    type: Sequelize.TEXT
  },
  password: {
    type: Sequelize.TEXT
  },
  status: {
    type: Sequelize.BIGINT,
    field: 'statusId',
  },
  date_of_birth: {
    type: Sequelize.DATE
  },
});

const Status = sequelize.define('statuses', {
  name: {
    type: Sequelize.TEXT
  },
});


const UserRate = sequelize.define('user_rates', {
  title: {
    type: Sequelize.TEXT
  },
  user: {
    type: Sequelize.BIGINT,
    field: 'userId'
  },
  comment: {
    type: Sequelize.TEXT
  },
  rate: {
    type: Sequelize.NUMBER
  },
});


User.belongsTo(Statuses, { foreignKey: 'statusId', as: 'userStatus'})

User.hasMany(UserRate, { foreignKey: 'userId', as: 'userRate' })

UserRate.findAll({ include: ['userRate']});

the query runs good, i get this:

 {
       title: 'test',
       rate: 4,
       user: 1,
       comment: 'test',
       userRate: {
          name: 'test',
          password: 'test',
          status: '1',
          date_of_birth: '11/22/1111',
       }
    }

but if i want to get this:

{
       title: 'test',
       rate: 4,
       user: 1,
       comment: 'test',
       userRate: {
          name: 'test',
          password: 'test',
          status: '1',
          date_of_birth: '11/22/1111',
          userStatus: {
             name: 'active',
             id: 1,
          }
       }
    }

i want to include status in the user object. I looked many places but i can't find a solution for this. i even try this:

UserRate.findAll({ include: ['userRate', 'userStatus]});

but that didn't work at all

i tried to use belongsToMany but i wasn't able to get it work, perhaps i'm not doing it right somehow. greatly appreciate any help

Upvotes: 0

Views: 1375

Answers (1)

Abhishek Shah
Abhishek Shah

Reputation: 864

UserRate does not doesn't have any direct association/relation with userStatus. So you to include it within User model.

UserRate.findAll({
    include: [{
        model: User, as: 'userRate',
        include: [{
            model: Status, as: 'userStatus',
        }],
    }],
});

Do not get confused by the array of object in include if you are seeing this for first time. You can include more models that should have association/relation defined with the parent that is including it.

Upvotes: 2

Related Questions