字符串作为 Sequelize/Postgres 外键时出错
Error With String as Sequelize/Postgres Foreign Key
我正在建立电站与其仪表读数之间的关系。 Postgres/Sequelize 期望外键的类型为 INTEGER
似乎有一个错误。我很乐意修复它。
型号
var Station = sequelize.define('Station', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
kin: DataTypes.STRING,
// other columns
var EKMreading = sequelize.define('EKMreading', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
"Meter": DataTypes.STRING,
// other columns
协会
EKMreading.belongsTo( Station, { as: 'KIN', foreignKey: 'kin'});
Station.hasMany( EKMreading, { as: { singular: 'reading', plural: 'readings'} } );
损坏的代码
EKMreading.create({ data blah, blah })
.then(function( reading ) {
Station.find({where: {ekmOmnimeterSerial: reading.Meter}})
.then(function( station ) {
reading.setKIN( station.kin ); // breaks stuff, see below
station.addReading( reading )
.then(function() {
console.log('Made relationship.');
});
});
});
错误(删节)
Error setting reading on Station. { [SequelizeDatabaseError: invalid input syntax for integer: "007-0020-001-04-K"]
总是简单的东西
根据错误,我认为我给出的主键是一个字符串有问题,但它想要一个整数。
真正的问题是您必须将整个实例传递给 setter:
// before
reading.setKIN( station.kin );
// after
reading.setKIN( station );
setter会自动从站里取主键,并赋值作为阅读中的外键
仍然未知
如何设置外键与另一个table的主键不同?例如,我怎样才能使读数上的外键对应于 Station 的 KIN 而不是其自动递增 ID?
我正在建立电站与其仪表读数之间的关系。 Postgres/Sequelize 期望外键的类型为 INTEGER
似乎有一个错误。我很乐意修复它。
型号
var Station = sequelize.define('Station', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
kin: DataTypes.STRING,
// other columns
var EKMreading = sequelize.define('EKMreading', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
"Meter": DataTypes.STRING,
// other columns
协会
EKMreading.belongsTo( Station, { as: 'KIN', foreignKey: 'kin'});
Station.hasMany( EKMreading, { as: { singular: 'reading', plural: 'readings'} } );
损坏的代码
EKMreading.create({ data blah, blah })
.then(function( reading ) {
Station.find({where: {ekmOmnimeterSerial: reading.Meter}})
.then(function( station ) {
reading.setKIN( station.kin ); // breaks stuff, see below
station.addReading( reading )
.then(function() {
console.log('Made relationship.');
});
});
});
错误(删节)
Error setting reading on Station. { [SequelizeDatabaseError: invalid input syntax for integer: "007-0020-001-04-K"]
总是简单的东西
根据错误,我认为我给出的主键是一个字符串有问题,但它想要一个整数。
真正的问题是您必须将整个实例传递给 setter:
// before
reading.setKIN( station.kin );
// after
reading.setKIN( station );
setter会自动从站里取主键,并赋值作为阅读中的外键
仍然未知
如何设置外键与另一个table的主键不同?例如,我怎样才能使读数上的外键对应于 Station 的 KIN 而不是其自动递增 ID?