简体   繁体   English

BelongsToMany 急切加载为每个关联返回多个对象

[英]BelongsToMany eager loading returns multiple objects for each association

I have two models: User and EconomicActivity.我有两个模型:用户和经济活动。 They are associated through UserEconomicActivity (it's a BelongsToMany relation).它们通过 UserEconomicActivity 关联(这是一个 BelongsToMany 关系)。 In User model, I have defined the association like this:在用户 model 中,我定义了这样的关联:

this.belongsToMany(models.EconomicActivity, {
  through: 'UserEconomicActivity',
  as: 'economicActivities',
  otherKey: {
    name: 'economicActivityId',
    allowNull: false
  },
  foreignKey: {
    name: 'userId',
    allowNull: false
  }
})

I'm trying to query User where it is associated with one or more EconomicActivity, like this:我正在尝试查询与一项或多项经济活动相关联的用户,如下所示:

const users = await User.findAll({
  include: [
    {
      model: EconomicActivity,
      as: 'economicActivities',
      where: {
        id: filters.economicActivities // This is an array with IDs I want to filter
      }
    }
  ],
  raw: true,
  nest: true
})

Let's say that one specific User is associated to 2 EconomicActivity.假设一个特定用户与 2 个经济活动相关联。 When I run this query, it returns the same user two times, one for each association.当我运行这个查询时,它会返回同一个用户两次,每个关联一个。 I want to return the same user just one time with an array of associated economicActivities inside it (like user.economicActivities).我想返回同一个用户一次,其中包含一系列相关的经济活动(如 user.economicActivities)。 Is this possible?这可能吗?

By setting raw to true, you're explicitly asking for this result format.通过将raw设置为 true,您明确要求使用这种结果格式。 I also don't see the use of nest here.我也没有在这里看到使用nest

I suggest you remove both parameters.我建议你删除这两个参数。

See the Sequelize API Reference for more info.有关详细信息,请参阅Sequelize API 参考

As I said in a comment, I needed to use raw and nest because I'm passing the data to Handlebars, and Handlebars can only output plain JavaScript objects, otherwise it gives me the error Handlebars: Access has been denied to resolve the property "name" because it is not an "own property" of its parent and will not output the data.正如我在评论中所说,我需要使用 raw 和 nest 因为我将数据传递给 Handlebars,而 Handlebars 只能 output 普通 JavaScript 对象,否则它会给我错误Handlebars: Access has been denied to resolve the property "name" because it is not an "own property" of its parent并且不会 output 数据。

But, I found a way to get a plain JavaScript object and also keeping all the associations inside an array:但是,我找到了一种方法来获得一个普通的 JavaScript object 并将所有关联保存在一个数组中:

await this.model.findAll(query).map(item => item.get({ plain: true }))

The model's get method does exactly what I want.该模型的get方法正是我想要的。 Because I'm using findAll , I use ES6 map method to call get from every model returned from the query.因为我使用的是findAll ,所以我使用 ES6 map 方法从查询返回的每个 model 中调用get

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM