gpt4 book ai didi

node.js - 如何在sequelize中获取一系列模型关联

转载 作者:搜寻专家 更新时间:2023-10-31 23:08:03 25 4
gpt4 key购买 nike

这是我的建筑

模型
var Buildings = sequelize.define('buildings', buildingsDefinition,
{
timestamps: true,
underscored: false,
paranoid: true,
indexes: [
{ fields: ['accId']}
],
engine: 'innodb',
classMethods:{
associate:function(models){
this.hasMany(models.Rooms, {
as: 'Rooms',
foreignKey: 'buildingId',
onUpdate: 'NO ACTION',
onDelete: 'NO ACTION',
constraints: false
})
}
}
}
);

在路由中,如何获取该模型的关联数组?

想要的结果,比如:

[
{'Rooms':
{
as: 'Rooms',
foreignKey: 'buildingId',
onUpdate: 'NO ACTION',
onDelete: 'NO ACTION',
constraints: false
}
}
]

类似Models.Buildings.classMethods

最佳答案

Sequelize 模型没有将关联列为数组的方法。但是由于模型包含有关关联和关联选项的信息,我们可以解析这些选项以获得所需的结果。

将模型对象传递给这样一个粗略的函数:

function modelAssociationsToArray(model) {
const result = [];

if (typeof model !== 'object' || typeof model.associations !== 'object') {
throw new Error("Model should be an object with the 'associations' property.");
}

Object.keys(model.associations).forEach((key) => {
const association = {};

// all needed information in the 'options' object
if (model.associations[key].hasOwnProperty('options')) {
association[key] = model.associations[key].options;
}

result.push(association);
});

return result;
}

我们可以获得类似这样的关联列表:

[
{
Product: {
foreignKey: [Object],
onDelete: 'restrict',
hooks: {},
useHooks: false,
timestamps: true,
...
hasPrimaryKeys: true,
onUpdate: 'CASCADE'
}
},
{
User: {
foreignKey: [Object],
onDelete: 'restrict',
hooks: {},
useHooks: false,
timestamps: true,
...
hasPrimaryKeys: true,
onUpdate: 'CASCADE'
}
}
]

关于node.js - 如何在sequelize中获取一系列模型关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39138512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com