我有2张 table 。
预订。
顾客。
我在 Booking 表中创建了 id_booking,因为我想创建唯一的 ID,不像 sequelize 中的 'id' 只是整数。
我如何从预订表中获得客户,有很多关系?
注意:外键不是id(来自sequelize)而是id_booking(string,unique)。
我的 Controller
enter code here
db.Booking.findAll({
include: [{
model: db.Customer
}]
})
我的模特
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;
};
非常感谢。
最佳答案
如果不想使用主键,则需要在 sourceKey
关联中指定 one to many,或在反向 targetKey
关系中指定 belongsTo()
。
Booking.hasMany(models.Customer, {
foreignKey: 'id_booking',
sourceKey: 'id_booking',
});
关于sequelize.js - 如何从Sequelize没有默认ID的另一个表中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52796989/