簡體   English   中英

使用帶有現有外鍵的 sequelize 插入一對多關系表

[英]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"});

我已經在 Sports 表中有一條記錄: {name: "Basketball", id: 1}我想在 Leagues 表中創建一條記錄,引用這個已經存在的運動記錄。 我怎么能用一個 function 做到這一點? 我瀏覽了文檔,但沒有找到任何合適的東西。 我知道如果我引用的記錄不存在,我可以通過以下方式進行操作:

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

對我來說,對於一個相對簡單的操作來說,代碼似乎太多了。 有什么“更聰明”或更短的方法嗎? 先感謝您!

我在stackoverflow上發現了類似的問題。 因此,除了手動查找 id 然后將其直接附加到新記錄之外,似乎沒有其他方法可以做到這一點。 但是,我做了一個快捷方式,以便更輕松地處理此類查詢。 So I created new class, which extended from the sequelize model class and added new static function which handles fetching of id by itself:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM