node.jssequelize.js

Sequealize.literal refering the model instead of the table


Is there any way to refer my model instead of the table on Sequelize.literal? Here I'm refering the table on the database but I would like to make a references directly using the model, in this case OModel or RModel.

const result = await OModel.findAll({
    where: { 
        requestId: requestId
    },
    include: {
        model: RModel,
        attributes: [
           'amount'      
        ]
    },
    attributes: [
        'id',
        'interest',
        [
            Sequelize.literal('`rtable`.`amount` * `otable`.`interest`'),
            'amountXInterest'
        ]
    ]
});

Solution

  • You can go the opposite way: to get the table name from a model at runtime and substitute it into a string passed to Sequelize.literal:

    // be aware it could be an object in case a model has an expilictly indicated schema,
    // see https://sequelize.org/api/v6/class/src/model.js~model#static-method-getTableName
    const oTableName = OModel.getTableName()
    const rTableName = RModel.getTableName()
    
    ..
    Sequelize.literal(`\`${rTableName}\`.\`amount\` * \`${oTableName}\`.\`interest\``)
    

    I suppose the same goes for column names if you also would like to get them from a model