1
votes

I have this two Sequelize models generated from the CLI

'use strict';
module.exports = function(sequelize, DataTypes) {
  var ticket_sold = sequelize.define('ticket_sold', {
    ticket_id: DataTypes.INTEGER,
    bus_id: DataTypes.INTEGER,
    departure: DataTypes.INTEGER,
    destination: DataTypes.INTEGER,
    passenger_id: DataTypes.INTEGER,
    amount: DataTypes.FLOAT,
    status: DataTypes.BOOLEAN,
    is_deleted: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
        
      }
    }
  });
  return ticket_sold;
};

and

'use strict';
module.exports = function(sequelize, DataTypes) {
  var locations = sequelize.define('locations', {
    name: DataTypes.STRING,
    status: DataTypes.BOOLEAN,
    is_deleted: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
        
      }
    }
  });
  return locations;
};

I need to associate the Departure and Destination to the Id of the location field. I could not just use the has many/belongsto as it creates another field.

I tried doing tickets_sold.departure.belongsTo(models.locations,{ onDelete:"CASCADE", foreignKey:{ allowNull:false } }) but it was of no use.

How can I associate the two fields with the location table?

1

1 Answers

0
votes

You need to use the targetKey property

From the docs :

The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model's primary key. To define a custom column, use the targetKey option.

So in your case you will need to do something like :

tickets_sold.belongsTo( models.locations, { targetKey: 'departure' } );
tickets_sold.belongsTo( models.locations, { targetKey: 'destination' } );