【问题标题】:Include more than one model relationship in findAll在 findAll 中包含多个模型关系
【发布时间】:2019-07-17 06:56:34
【问题描述】:

我正在尝试使用 findAll 从数据库中获取一些详细信息,但我想包含来自我添加到 include 语句中的模型的关系。

我有一个产品表,我正在获取产品并包含发布该项目的用户,但该用户有个人资料,因此我想在获取产品时包含用户个人资料 像

Product: {
  name: 'TV',
  User: {
    username:"someUserName",
    Profile: {
      image: 'a random image'
    }
  }
}

我尝试添加要包含的模型,但它不起作用

const results = await Product.findAll({
    include: [{
        model: User,
        as: 'Seller',
        attributes:{
            exclude: ['password'],
        }
    }]
});
            return results;

【问题讨论】:

  • 这不是stackoverflow.com/questions/24282990/…的复制品吗?
  • 我的关系没有使用 id 作为外键它使用用户名我如何将其更改为指向该用户名
  • 查看原始问题中如何定义外键并指定用户名,如图所示

标签: sequelize.js


【解决方案1】:

您需要在include 中添加include。实现见下文

const results = await Product.findAll({
  include: [{
    model: User,
    include: [ModelAssociatedToUser],
    as: 'Seller',
    attributes:{
      exclude: ['password'],
    }
  }],
});

【讨论】:

    猜你喜欢
    • 2018-07-20
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多