Oscar Hermawan
Oscar Hermawan

Reputation: 13

How to get data from another table without default ID from Sequelize?

I have 2 tables.

Booking.

  1. id = integer (default from sequelize)
  2. id_booking = string

Customer.

  1. id = integer (default from sequelize)
  2. id_booking = string
  3. agent = string

I create id_booking in Booking table, because I want to create unique ID, isnt like 'id' from sequelize just integer.

How can I get customer from Booking table, with hasmany relation? note : the foreign key isnt id (from sequelize) but id_booking(string, unique).

My Controller

enter code here
db.Booking.findAll({
  include: [{
    model: db.Customer
  }]
})

My Model

  module.exports = (sequelize, DataTypes) => {
  const Booking = sequelize.define('Booking', {
    id_booking: DataTypes.STRING,
    agent:DataTypes.STRING,
  }, {});
  Booking.associate = function(models) {
    Booking.hasMany(models.Customer, { foreignKey: 'id_booking'})
  };
  return Booking;
};

Thank you so much.

Upvotes: 0

Views: 2336

Answers (1)

doublesharp
doublesharp

Reputation: 27657

If you don't want to use the primary key then you need to specify the sourceKey in your one to many associations, or the targetKey in the reverse belongsTo() relationship.

Booking.hasMany(models.Customer, {
  foreignKey: 'id_booking', 
  sourceKey: 'id_booking',
});

Upvotes: 1

Related Questions