如何使用 sequelize.js 从关联模型中加载属性

Posted

技术标签:

【中文标题】如何使用 sequelize.js 从关联模型中加载属性【英文标题】:How to load attributes from associated models with sequelize.js 【发布时间】:2020-05-13 10:02:10 【问题描述】:

我正在用两个模型简化当前项目。

自助服务终端模式

module.exports = function(sequelize, DataTypes) 
    return sequelize.define('kiosk', 
        id: 
            type: DataTypes.BIGINT,
            allowNull: false,
            primaryKey: true,
            autoIncrement: true
        ,
        name: 
            type: DataTypes.STRING(150),
            allowNull: false
        ,
    , 
        tableName: 'kiosk',
        timestamps: false,
        underscored: true
    );
;

收据模型

module.exports = function(sequelize, DataTypes) 
    return sequelize.define('receipt', 
        id: 
            type: DataTypes.STRING(255),
            allowNull: false,
            primaryKey: true
        ,
        kiosk_id: 
            type: DataTypes.BIGINT,
            allowNull: false,
            references: 
                model: 'kiosk',
                key: 'id'
            
        ,
        customer_id: 
            type: DataTypes.BIGINT,
            allowNull: false,
            references: 
                model: 'customer_type',
                key: 'id'
            
        ,
        total: 
            type: DataTypes.DECIMAL,
            allowNull: false
        ,
    , 
        tableName: 'receipt',
        timestamps: false,
        underscored: true
    );
;

模型被缩小以简化问题

我的协会

models.receipt.belongsTo(models.kiosk, 
    as: 'kiosk'
);
models.kiosk.hasMany(models.receipt, 
    as: 'receipt'
);

最终查询:

const Kiosk = require('../models').kiosk;
const R = ReceiptModel = require('../models').receipt;
try 
        let receiptModels =  await ReceiptModel.findAll(
            raw: true,
            attributes: [['kiosk.name', 'KioskName']],
            include: [
                model: Kiosk,
                required: false,
                as: 'kiosk',
                attributes: []
            ],
        );
        return res.json(receiptModels);
    catch(err)
        // I am getting Error
        return res.status(500).send( msg: err.message );
    

我的期望:

receiptModels = [
    KioskName: 'MyKioskName#1'
    ,
    KioskName: 'MyKioskName#2'
    ,
    KioskName: 'MyKioskName#3'
    ,
];

但是,我收到以下错误:


  "name": "SequelizeDatabaseError",
  "parent": 
    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlState": "42S22",
    "sqlMessage": "Unknown column 'kiosk.name' in 'field list'",
    "sql": "SELECT `kiosk.name` AS `KioskName` FROM `receipt` AS `receipt` LEFT OUTER JOIN `kiosk` AS `kiosk` ON `receipt`.`kiosk_id` = `kiosk`.`id` WHERE `receipt`.`created_at` >= '2020-01-20 05:00:00' LIMIT 2;"
  ,
  "original": 
    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlState": "42S22",
    "sqlMessage": "Unknown column 'kiosk.name' in 'field list'",
    "sql": "SELECT `kiosk.name` AS `KioskName` FROM `receipt` AS `receipt` LEFT OUTER JOIN `kiosk` AS `kiosk` ON `receipt`.`kiosk_id` = `kiosk`.`id` WHERE `receipt`.`created_at` >= '2020-01-20 05:00:00' LIMIT 2;"
  ,
  "sql": "SELECT `kiosk.name` AS `KioskName` FROM `receipt` AS `receipt` LEFT OUTER JOIN `kiosk` AS `kiosk` ON `receipt`.`kiosk_id` = `kiosk`.`id` WHERE `receipt`.`created_at` >= '2020-01-20 05:00:00' LIMIT 2;"

注意:我的帖子与这篇类似,尽管它(帖子)不能解决我的问题。这是紧急情况,根据 *** 政策,我们不应该在关闭的问题上发布。 Load attributes from associated model in sequelize.js

【问题讨论】:

奇怪的是,当我从错误中复制 sql 并在没有反引号字符的情况下执行它时,我得到了所需的响应。请问有人有什么想法吗? 【参考方案1】:

我使用sequelize.col() 函数让它工作。

以下是最终/有效的查询代码:

try 
        let receiptModels =  await ReceiptModel.findAll(
            raw: true,
            attributes: [[Sequelize.col('kiosk.name'), 'Kiosk']],
            include: [
                model: Kiosk,
                required: false,
                as: 'kiosk',
                attributes: []
            ],
        );
        return res.json(receiptModels);
    catch(err)
        return res.status(500).send( msg: err.message );
    

【讨论】:

应该使用 sequelize.col 而不是“纯点符号”,如此答案:***.com/questions/21883484/… 这很有见地。感谢分享。

以上是关于如何使用 sequelize.js 从关联模型中加载属性的主要内容,如果未能解决你的问题,请参考以下文章

使用 Sequelize.js 和 PostgreSQL 在关联模型上查询 JSONB 字段

Node.js / Sequelize.js / Express.js - 如何插入多对多关联? (同步/异步?)

使用 Sequelize.js 时在哪里定义关联/关系?

从已经定义的模型中获取 Sequelize.js ENUM 值

在 sequelize.js 中获取与 belongsToMany 的关联

如何在 sequelize.js 中有条件地加载关联?