How to load attributes from associated models with sequelize.js

倖福魔咒の 提交于 2021-01-24 09:35:08

问题


I am simplify the current project with two models.

Kiosk model

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
    });
};

Receipt model

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 are minified to simplify the problem

My Associations

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

Final query:

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 });
    }

What I am expecting:

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

But, I am getting the following errors:

{
  "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;"
}

NB: My post is similar with this one though it (the post) doesn't fix my problem. And this an emergency and according to StackOverflow policy we shouldn't post on a close issue. Load attributes from associated model in sequelize.js


回答1:


I have it working by using sequelize.col() function.

Following is the final/working query code:

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 });
    }


来源:https://stackoverflow.com/questions/59941122/how-to-load-attributes-from-associated-models-with-sequelize-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!