使用带有现有外键的 sequelize 插入一对多关系 table

Insert into one-to-many relationship table using sequelize with existing foreign key

我有以下型号:

Sports.init({
        name: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        }
    }, {sequelize, tableName: 'sports'});
    
Leagues.init({
        name: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        }
    }, {sequelize, tableName: 'leagues'});

它们之间的关联如下

Sports.Leagues = Sports.hasMany(Leagues, {foreignKey: {name: "sports_id", allowNull: false}, sourceKey: "id"});
Leagues.Sports = Leagues.belongsTo(Sports, {foreignKey: {name: "sports_id", allowNull: false}, targetKey: "id"});

我已经有运动会记录table:{name: "Basketball", id: 1} 我想在联赛中创造一项记录 table 参考这个已经存在的体育记录。 我怎样才能用一个功能做到这一点?我浏览了文档,但没有找到合适的内容。我知道我可以通过以下方式执行此操作,以防万一我引用的记录不存在:

await Leagues.create({name: leagueName, espn_name: espnName, Sport: {name: "Basketball"}}, {include: Leagues.Sports});

但是,如果外键已经存在,除了手动执行以下操作外,我没有找到任何有关如何执行此操作的信息:

await Sports.findOne({where: {name: sportName}}).then((res) => {
        if(res) {
            return Leagues.create({name: leagueName, espn_name: espnName, sports_id: res.get("id")});
        }
    });

对我来说,对于一个相对简单的操作来说,代码似乎太多了。是否有任何“更聪明”或更短的方法来做到这一点? 提前致谢!

I found similar question on Whosebug. 所以除了手动查找 id 然后将其直接附加到新记录之外,似乎没有其他方法可以做到这一点。但是,为了更轻松地处理此类查询,我创建了一个快捷方式。所以我创建了新的 class,它从 sequelize 模型 class 扩展而来,并添加了新的静态函数,它自己处理 id 的获取:

export class CustomModel extends Model {
    static async getId<M extends Model>(attributes: M['_creationAttributes']) {
        const res = await this.findOne({where: attributes});
        if(!res) {
            throw new Error(`Can not find id of the record in the table ${this.tableName}`);
        }
        return res.get("id")
    }
}

我的模型现在从这个扩展 class:

export class Sports extends CustomModel{
    static Leagues: HasMany<Sports, Leagues>;
}

Sports.init({
        name: {
            type: DataTypes.STRING,
            unique: true,
            allowNull: false
        }
    }, {sequelize, tableName: 'sports'});

所以现在可以使用更少的代码添加具有现有密钥的新记录:

 await Leagues.create({name: "u", sports_id: await Sports.getId({name: "Basketball"})});