【问题标题】:Adding attributes and values from another model via sequelize通过 sequelize 从另一个模型添加属性和值
【发布时间】:2019-02-08 00:47:33
【问题描述】:

我正在使用 sequelize,我希望我的结果 (JSON) 看起来像那样(请参阅:WantResult)。是否有可能通过修改我的函数来完全恢复那个 JSON?

这是我的功能:

try {
          const mediImport = await User.findOne({

            where: { Id: 1 },
            // Select forename as Vorname, name as Nachname
            attributes: [['forename', 'Vorname'], ['name', 'Nachname']],
            include: {
              model: SurveyResult,
              attributes: ['result', 'result'] }

          })

这是我的结果:

    {
    "Person": {
        "Vorname": "Mustermann",
        "Nachname": "Max",
        "SurveyResult": {
            "result": {
                "birthdate": "01.01.1990",
                "Sind Sie miteinander verheiratet?": "Ja",
                "Waren Sie wegen Ihres Kinderwunsches bereits in ärztlicher Behandlung?": "Ja"
            }
        }
    }
}

WantResult:但我希望我的结果看起来像这样

Person": {
        "Vorname": "Mustermann",
        "Nachname": "Max",
        "birthdate": "01.01.1990" 

【问题讨论】:

  • 试试这个:attributes: [['forename', 'Vorname'], ['name', 'Nachname'] , ['SurveyResult.result.birthdate' , 'birthdate']],
  • 那没用。 SurveyResult 是另一个模型。我收到此错误:'未知列 \'SurveyResult.result.birthdate\' in \'field list\'',

标签: mysql node.js sequelize.js


【解决方案1】:

你必须做这样的事情(这适用于birthdaySurveyResult的属性并且不在result内的情况):

try {
  const mediImport = await User.findOne({

    where: { Id: 1 },
    // Select forename as Vorname, name as Nachname
    attributes: [
        ['forename', 'Vorname'], 
        ['name', 'Nachname'],
        [sequelize.literal('"SurveyResult"."birthdate"'), 'birthdate']
    ],
    include: {
        model: SurveyResult,
        attributes: [] 
    }
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2012-03-22
    相关资源
    最近更新 更多