Josef Henn
Josef Henn

Reputation: 162

Adding attributes and values from another model via sequelize

Im using sequelize i want that my result (JSON) looks like that (see: WantResult). is it possible to get back exactly that JSON by modifing my function?

Here is my function:

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'] }

          })

Here is my 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: But i want that my result looks like that

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

Upvotes: 0

Views: 1841

Answers (1)

Ellebkey
Ellebkey

Reputation: 2301

You have to do something like this (This works in the case that birthday is an attribute from SurveyResult and is not inside 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: [] 
    }
  })
}

Upvotes: 1

Related Questions