Sequelize eagerly create() with existing associated Id in reference table by column name

Viewed 58

Is there a way to eagerly get id by name through association without creating row in association?

Let's say I have association

module.exports = (sequelize, DataTypes) => {
    const ApiKey = sequelize.define(
        "ApiKey",
        {
            id: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true,
                allowNull: false,
            },
            PermissionId: {
                type: DataTypes.INTEGER,
            },
        },
        {
            timestamps: true,
        }
    );

    ApiKey.associate = function (models) {
        ApiKey.belongsTo(models.Permission);
    };

    return ApiKey;
};

I want to be able to get this in one query:

models.ApiKey.create(
    {
        PermissionId: 'Automatically get ID by some select',
    },
    {
        include: [{ model: models.Permission }],
    }
);

I am able to get it like this (which I don't want):

models.ApiKey.create(
    {
        PermissionId: literal(
                        `(SELECT id FROM Permission WHERE name = 'guest')`
                    ),,
    },
);
0 Answers
Related