【问题标题】:Sequelize Model.associations[alias]. There is another way to get associated models?续集 Model.associations[别名]。还有另一种获取关联模型的方法吗?
【发布时间】:2020-08-23 10:53:20
【问题描述】:

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

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

这样,效果很好。

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

但是如果想做这样的事情:

Model.findAll({
    include:[
         {
            model: 'partner',
            where: {id:2}
         }
    ]
})

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

【问题讨论】:

  • 你在这里传递什么`模型:......,`你也可以显示你的关联设置吗?
  • 嗨@SujeetAgrahari,要完成这项工作,我需要传递模型类,但是,我想在模型属性中传递一个字符串,就像我只有一个数组一样:{include:[ '模型1','模型2','模型3']}。我刚刚编辑了帖子。谢谢

标签: sequelize.js


【解决方案1】:

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

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.

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    • 2012-05-10
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2013-04-04
    相关资源
    最近更新 更多