通过sequelize从另一个模型添加属性和值

时间:2019-02-07 13:40:32

标签: mysql node.js sequelize.js

我正在使用续集,我希望我的结果(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" 

1 个答案:

答案 0 :(得分:0)

您必须执行类似的操作(如果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: [] 
    }
  })
}