1 回答
TA贡献1936条经验 获得超6个赞
你可以这样做。你没有包括额外的contact_phone你可以直接用这样的联系和电话来做。
触点模块:
module.exports = (sequelize) => {
const Contact = sequelize.define(
'contact',
{
contact_id: {
type: Sequelize.INT,
primaryKey: true,
autoIncrement: true,
field: 'contact_id'
},
first_name: {
type: Sequelize.STRING,
field: 'first_name'
},
last_name: {
type: Sequelize.STRING,
field: 'last_name',
},
created_at: {
type: Sequelize.DATE,
field: 'created_at'
},
updated_at: {
type: Sequelize.DATE,
field: 'updated_at'
}
},
{
tableName: 'contacts',
freezeTableName: true,
}
);
Contact.associate = (models) => {
Contact.hasOne(models.phone, { // has many or hasOne relationship .here read like contact has one phone
foreignKey: 'phone_id',
onDelete: "CASCADE"
});
};
return Contact;
};
手机模块:
module.exports = (sequelize) => {
const Phone = sequelize.define(
'phone',
{
phone_id: {
type: Sequelize.INT,
primaryKey: true,
autoIncrement: true,
field: 'phone_id'
},
contact_id: {
type: Sequelize.INT,
},
updated_at: {
type: Sequelize.DATE,
field: 'updated_at'
},
created_at: {
type: Sequelize.DATE,
field: 'created_at'
}
},
{
tableName: 'phones',
freezeTableName: true,
}
);
Phone.associate = (models) => {
Phone.belongsTo(models.contact, {
foreignKey: 'contact_id',
as: 'contact',
onDelete: "CASCADE"
});
};
}
您的查询如下所示:
models.contact.findAll({
include: [
{
model: models.phone,
as: 'contact'
}
]
}).then(contacts => {
res.status(200).send(contacts);
});
编辑:
如何定义具有相同键和不同别名的更多关联
Phone.associate = (models) => {
Phone.belongsTo(models.contact, {
foreignKey: 'contact_id',
as: 'contact',
onDelete: "CASCADE"
});
Phone.belongsTo(models.contact, {
foreignKey: 'contact_id',
as: 'phone',
onDelete: "CASCADE"
});
};
添加回答
举报