【问题标题】:Multiple includes in one model querying一个模型中的多个包含查询
【发布时间】:2021-10-31 04:06:22
【问题描述】:

对不起我的英语。 我想使用 sequelize 在 findOne 中进行多个包含关联。 当我分开时,一切都完美无缺。我将在下面对比哪些有效,哪些无效。

// that doesn't work
const post = await Post.findOne({
         where: { post_url: post_url },
         include: { // this include dont work
            association: 'postAuthor',
            attributes: ['name'],
         },
         include: {
            association: 'comments',
            attributes: ['comment'],
            include: {
               association: 'commentAuthor',
               attributes: ['name']
            }
         }
      });

但如果我将每个句子分开,它会起作用

// this work
     include: {
            association: 'postAuthor',
            attributes: ['name'],
         },

再次为英语感到抱歉。

简而言之,我需要同时让这两个包含工作。 include 中的 include 完美运行(commentAuthor 在 cmets 中)。

【问题讨论】:

  • 根据文档include 可以是关联对象的数组。 sequelize.org/master/manual/eager-loading.htm
  • 非常感谢丹尼尔!这解决了我的问题,我在文档中找不到它。我将编辑该出版物并保持原样,以防将来有人遇到此问题。
  • 无需编辑您的问题以添加您的解决方案,您可以自行回答,因为 Stackoverflow 是一个问答环节

标签: javascript node.js sequelize.js


【解决方案1】:
      where: { post_url: post_url },
         include: [
            { association: 'postAuthor', attributes: ['name'] },
            {
               association: 'comments', attributes: ['comment'],
               include: [{
                  association: 'commentAuthor',
                  attributes: ['name']
               }]
            }
         ]
      });

【讨论】:

    猜你喜欢
    • 2015-01-08
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多