0
votes

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.

1

1 Answers

0
votes

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',
});