【问题标题】:associate existing fields from class methods sequelize关联类方法中的现有字段 sequelize
【发布时间】:2016-07-28 17:10:07
【问题描述】:

我有这两个从 CLI 生成的 Sequelize 模型

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

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

我需要将 Departure 和 Destination 与 location 字段的 Id 相关联。我不能只使用 has many/belongsto,因为它会创建另一个字段。

我试着做 ticket_sold.departure.belongsTo(models.locations,{ onDelete:"级联", 外键:{ 允许空:假 } }) 但是没有用。

如何将这两个字段与位置表相关联?

【问题讨论】:

    标签: node.js orm sequelize.js sequelize-cli


    【解决方案1】:

    您需要使用targetKey property

    来自文档:

    目标键是源模型上的外键列指向的目标模型上的列。默认情况下,belongsTo 关系的目标键将是目标模型的主键。要定义自定义列,请使用 targetKey 选项。

    因此,在您的情况下,您需要执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 2020-07-24
      • 2021-12-27
      • 2022-01-15
      相关资源
      最近更新 更多