Далее, как вернуть столбец объединенной таблицы в результаты - PullRequest
0 голосов
/ 08 апреля 2020

Я использую модуль sequelize для моего node.js mvc проекта, и запрос, который я хотел бы выполнить, следующий:

SELECT answer_text, isNew, name FROM answer JOIN topic ON answer.topic_id = topic.id

answer_text и isNew - это столбцы таблица ответов, в то время как name - это столбец, который существует только в таблице topi c.

Как можно, чтобы столбец topi c table name появился в результатах рядом с isNew столбец, чтобы я мог легко получить к нему доступ? Предоставляет ли sequelize такую ​​функцию или я отвечаю за форматирование результата?

Я пытался добавить различные атрибуты, такие как 'topi c .name', но ни одна из них не сработала.

Способ, которым я настроил структуру файла, основан на их документации Последовательное использование с express

var models = require('../models')

var answers = await models.Answer.findAll({
    include: [{
        model: models.Topic
    }],
    attributes: [
        'answer_text',
        'isNew'
    ]
})
console.log(answers)

Вывод следующего:

{ answer_text: 'maybe it is robots',
  isNew: true,
  Topic:
   Topic {
     dataValues:
      { id: 830,
        mid: 'm.0bjmp5',
        name: 'Robot Arena',
        description:
         'Robot Arena is a computer game made by Infogrames. It features robotic combat similar to that of Battlebots Robotica and Robot Wars. There are a number of different chassis and on top of that there are numerous attachments. Weapons accessories tires and other forms of mobility batteries and air tanks are among the customization choices. A sequel called Robot Arena 2 Design and Destroy was made which allows for total customization of your 
robot.',
        type: 'cvg.computer_videogame' },
     _previousDataValues:
      { id: 830,
        mid: 'm.0bjmp5',
        name: 'Robot Arena',
        description:
         'Robot Arena is a computer game made by Infogrames. It features robotic combat similar to that of Battlebots Robotica and Robot Wars. There are a number of different chassis and on top of that there are numerous attachments. Weapons accessories tires and other forms of mobility batteries and air tanks are among the customization choices. A sequel called Robot Arena 2 Design and Destroy was made which allows for total customization of your 
robot.',
        type: 'cvg.computer_videogame' },
     _changed: {},
     _modelOptions:
      { timestamps: false,
        validate: {},
        freezeTableName: false,
        underscored: false,
        paranoid: false,
        rejectOnEmpty: false,
        whereCollection: null,
        schema: null,
        schemaDelimiter: '',
        defaultScope: {},
        scopes: {},
        indexes: [],
        name: [Object],
        omitNull: false,
        sequelize: [Sequelize],
        hooks: {} },
     _options:
      { isNewRecord: false,
        _schema: null,
        _schemaDelimiter: '',
        include: undefined,
        includeNames: undefined,
        includeMap: undefined,
        includeValidated: true,
        raw: true,
        attributes: undefined },
     isNewRecord: false } }

Ответы [ 2 ]

1 голос
/ 08 апреля 2020

Пожалуйста, попробуйте следующее утверждение sequelize -

var answers = await models.Answer.findAll({
    include: [{
        model: models.Topic,
    attributes: ['name']
    }],
    attributes: [
        'answer_text',
        'isNew'
    ],
    raw: true
})

Надеюсь, это поможет!

0 голосов
/ 08 апреля 2020

Рабочий ответ:

Чтобы использовать [sequelize.col('Topic.name'), 'name'] внутри атрибутов, необходимо использовать секвелиз, чтобы мы могли извлечь name столбец таблицы Topi c и переименовать 'Темы .name 'к имени. (Пробовал models.col, но это не функция)

raw: true требуется, если вы хотите получить только столбцы внутри answers[0]

attributes:[] необходимо включить, потому что если Вы не ставите его, в результате будут включены все столбцы из объединенной таблицы (Topi c).

const models = require('../models')
const sequelize = require('sequelize');

var answers = await models.Answer.findAll({
                include: [{
                    model: models.Topic,
                    attributes: []
                }],
                attributes: [
                    'answer_text',
                    'isNew',
                    [sequelize.col('Topic.name'), 'name']
                ],
                raw: true
            })
console.log(answers[0])

output:

{ answer_text: 'robot arena',
  isNew: 'true',
  name: 'Robot Arena' }
...