Return flat object from sequelize with association

后端 未结 3 1949
醉梦人生
醉梦人生 2021-01-14 08:21

I am working on converting all my queries in sequelize. The problem I have come across is that when select queries include associations (ex. one to many), the object I get

3条回答
  •  攒了一身酷
    2021-01-14 09:05

    Old question, but as I was attempting to do this also and found a pure sequelize solution that does not require the "after" mapping, I wanted to add that here. So to have sequelize itself return the desired object format, it would be this, where the attributes are explicitly assigned based off column return values from the include table:

    models.table1.findAll({
        attributes: [
          'field1', 
          'field2',
          [sequelize.col('models.assoc_table.field_a'), 'field_a'], // Set key
          [sequelize.col('models.assoc_table.field_b'), 'field_b'], // Set key
        ],
        where: {field1: someval},
        include: [
         {model: models.assoc_table, 
          required: true, 
          attributes:[], // Explicitly do not send back nested key's
         }
       ]
    })
    

提交回复
热议问题