Javascript 在Sequelize中使用classMethods时有没有更简洁的方法?
我有一个模型Javascript 在Sequelize中使用classMethods时有没有更简洁的方法?,javascript,express,sequelize.js,Javascript,Express,Sequelize.js,我有一个模型intent,它有一个与条件和链接以及节点的关联。节点本身也与链接有关联 通过快速路线,我想在一个物体中获得所有信息。我现在做这件事的方式很老套,很难理解。这是可行的,但我希望有更好的方式来写这类东西 app.get('/api/intents/:id', function(req, res) { models.intent.findOne({ where: { id: req.params.id } })
intent
,它有一个与条件和链接以及节点的关联。节点
本身也与链接
有关联
通过快速路线,我想在一个物体中获得所有信息。我现在做这件事的方式很老套,很难理解。这是可行的,但我希望有更好的方式来写这类东西
app.get('/api/intents/:id', function(req, res) {
models.intent.findOne({
where: {
id: req.params.id
}
})
.then(function(intent) {
intent.getConditions() // call generated function from intent model for conditions
.then(function(conditions) {
intent.getLinks() // then call generated function from intent model for links
.then(function(links) {
intent.getNodes() // then call generated function from nodes model for links
.then(function(nodes) {
Promise.map(nodes, function(node) {
return node.getLinks() // Even deeper nested and getting out of hand
.then(function(links) {
node.setDataValue('links', links)
})
})
.then(function() {
intent.setDataValue('conditions', conditions)
intent.setDataValue('links', links)
intent.setDataValue('nodes', nodes)
res.json(intent)
})
})
})
})
})
})
您可以使用等待所有承诺得到解决,然后对数据进行处理
下面是让您步入正轨的部分示例:
app.get('/api/intents/:id', function(req, res) {
models.intent.findOne({
where: {
id: req.params.id
}
})
.then(function(intent) {
let promises = []
promises.push(intent.getConditions())
promises.push(intent.getLinks())
promises.push(intent.getNodes())
Promise.all(promises)
.then(function(resolvedPromises) {
Promise.map(resolvedPromises, function(node) {
intent.setDataValue('conditions', resolvedPromises[0])
intent.setDataValue('links', resolvedPromises[1])
...
})
})
})
我认为您完全没有将的概念包括在选项中方法的对象中,比如findOne
。只用
models.intent.findById(req.params.id, {
include: [
{ model: models.condition },
{ model: models.link },
{ model: models.node, include: [ { model: models.link } ]
]
}).then((intent) => {
// here you get intent with conditions, links and nodes with links
});
另一种方法是在模型上定义和使用。这似乎好得多,除了疏远的resolvedPromises数组。我会实现的,干杯。你的方法更好。哦,哇,我想我被自动生成的函数弄瞎了。这太完美了,谢谢。