javascript - Sequelize如何在结果中返回连接表的列

标签 javascript sql node.js model-view-controller sequelize.js

我正在为我的node.js mvc项目使用sequelize模块,我想要执行的查询如下

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

answer_textisNew 是答案表的列,而 name 是仅存在于主题表中的列。

如何让主题表 name 列出现在 isNew 列旁边的结果中,以便我可以轻松访问它? Sequelize 是否提供这样的功能,或者我有责任格式化结果?

我尝试在“topic.name”等属性中添加各种内容,但没有成功。

我设置文件结构的方式基于他们的文档 Sequelize usage with 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 } }

最佳答案

工作答案:

必须需要 Sequelize 才能在属性内使用 [sequelize.col('Topic.name'), 'name'] 以便我们可以获取 name 列主题表并将“Topics.name”重命名为 name。 (尝试了 models.col 但它不是一个函数)

如果您只想获取 answers[0] 中的列,则需要

raw: true

attributes:[] 在 include 内是必需的,因为如果不放置它,结果将包含连接表(主题)中的所有列。

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])

输出:

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

关于javascript - Sequelize如何在结果中返回连接表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61097455/

相关文章:

mysql - SQL CASE 比较 Text Datarow 和 Int Datarow

testing - Node.js 测试 RESTful API(vows.js?)

node.js - 在 NestJS HTTP 服务器中使用子进程时,受 CPU 限制的进程会阻塞工作池

javascript - React 输入设置状态 onChange 设置多个状态属性

mysql - SELECT 按字段中的值分组

JavaScript 内存泄漏。由于函数变量,对象未被删除

mysql - 根据结果​​表中的顺序更新行

node.js - Laravel 混合 : ValidationError: CSS Loader has been initialized using an options object that does not match the API schema

javascript - 显示更多按钮

javascript - Express:模板引擎 (Pug) 调用的样式/脚本未加载