Noor Fathima
Noor Fathima

Reputation: 67

Remove prefix tablename in join query result

Using nodejs(10.15.0),sequelize (4.42.0) and MySQL, am trying the remove table path from the result in join query.

Table1
    .findAll({
      attributes: ['id', 'name', 'other'],
      include: [{
        attributes: ['code_id'],
        model: Table2,
        nested: false,
        required: true,
      }],
      raw: true,
    })

Query Result

[
  {
    "id": 1,
    "name": "stuff",
    "other": true,
    "table2.code_id": 1,
  }
]

Expecting to happen

      [
  {
    "id": 1,
    "name": "stuff",
    "other": true,
    "code_id": 1,
  }
]

Upvotes: 0

Views: 3057

Answers (1)

doublesharp
doublesharp

Reputation: 27637

Remove raw: true, - it is preventing Sequelize from parsing the results into objects. If you don't want to use a Model Instance you will need to write your own parser for the results.

Note that it will parse into the following structure ("table2" will be a property):

[
  {
    "id": 1,
    "name": "stuff",
    "other": true,
    "table2": {
      "code_id": 1,
    }
  }
]

Alternatively you could alias the child row, but note that it will go into the dataValues only unless you create a VIRTUAL field that maps to it.

Table1
.findAll({
  attributes: [
    'id', 'name', 'other',
    [sequelize.col('table2.code_id'), 'code_id'], // aliased here
  ],
  include: [{
    attributes: [],
    model: Table2,
    required: true,
  }],
  raw: true,
})

Upvotes: 3

Related Questions