gpt4 book ai didi

sequelize.js - Sequelize Model.associations[别名]。还有另一种获取关联模型的方法吗?

转载 作者:行者123 更新时间:2023-12-03 22:35:19 25 4
gpt4 key购买 nike

我试图弄清楚是否使用模型类(不是实例),我可以获得与相应类的所有相关关联(belongsTo、hasOne、hasMany 等)。我发现没有记录的 Model.associations 属性,所以如果可能的话,我想避免使用它。你们知道如何得到这个结果吗?

我的目标,它只是在查询中传递一个字符串作为模型,并仍然设置其他属性,例如 where 条件。

这样,工作正常。

Model.findAll({
include:['partner']
})

但是如果想做这样的事情:
Model.findAll({
include:[
{
model: 'partner',
where: {id:2}
}
]
})

我需要导入模型,这很好,它也可以工作。我只想传递一个字符串并在更高的类中解析,因为继续导入模型很烦人,并且在没有这么多条件的情况下不可能动态包含。

最佳答案

如果您想包含模型,而不导入它。您可以通过在关联上定义别名来做到这一点。

User.hasMany(models.Tool, { as: 'Instruments'}); // here Intruments is alias to Tool

您还可以通过指定与关联别名匹配的字符串来按别名包含:
User.findAll({ include: 'Instruments' }); // Also works
User.findAll({ include: { association: 'Instruments' } }); // Also works

输出:
[{
"name": "John Doe",
"id": 1,
"Instruments": [{
"name": "Scissor",
"id": 1,
"userId": 1
}]
}]

欲了解更多信息 read here.

关于sequelize.js - Sequelize Model.associations[别名]。还有另一种获取关联模型的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61669724/

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