Home > database >  sequelize : how rename column in include
sequelize : how rename column in include

Time:06-06

I have this query :

    const data = await modelOwners.findAll({
  attributes: ["id", "name", "email"],
  include: [
    {
      model: modelLotsTantiemes,
      as: "LotsOwner",
      attributes: [
        "lotId",
        ["distributionKeyId", 'costKey'],
        [ Sequelize.fn('sum', Sequelize.col("tantiemeNumber")), 'totalTantieme' ],
      ],
    },
  ],
  where: { coproNumber: req.header("customerId")},
  group: ["name", "LotsOwner.distributionKeyId"],
  raw: true,
  nest: false,
  order: [["name", "ASC"]],
});

When I test it on Postman Y have this result :

"data": [
    {
        "id": 4,
        "name": "Clement Tine",
        "email": "[email protected]",
        "LotsOwner.field1": 2,
        "LotsOwner.field2": 1,
        "LotsOwner.field3": "1892"
    },
    {
        "id": 6,
        "name": "Léo Pard",
        "email": "[email protected]",
        "LotsOwner.field1": 9,
        "LotsOwner.field2": 1,
        "LotsOwner.field3": "4432"
    }]

But I would like an other name for my columns like :

"data": [
    {
        "id": 4,
        "name": "Clement Tine",
        "email": "[email protected]",
        "field1": 2,
        "field2": 1,
        "field3": "1892"
    }]
  

I don't want the name of the association alias. Do you know if there is an option to do it ?

CodePudding user response:

If you wish to have attributes of an associated model on the same level as the main model then you need to include them manually indicating the associated model name:

const data = await modelOwners.findAll({
  attributes: ["id", "name", "email",
  [Sequelize.col('"LotsOwner"."distributionKeyId"'), 'costKey']
  ],
  include: [
    {
      model: modelLotsTantiemes,
      as: "LotsOwner",
...
  • Related