簡體   English   中英

Sequelize M:N 關聯不通過表記錄創建

[英]Sequelize M:N association not creating through table record

當我使用 through 選項創建帶有關聯標簽的食譜時,我連接到的 mysql 數據庫的連接表中沒有創建任何記錄。

這是我的模型定義:

export const Recipe = sequelize.define('Recipe', {
    // Model attributes are defined here
    title: {
        type: DataTypes.STRING,
        allowNull: false
    },
    image: {
        type: DataTypes.STRING,
        allowNull: true
    },
    prepTime: {
        type: DataTypes.DOUBLE,
        allowNull: false
    },
    cookTime: {
        type: DataTypes.DOUBLE,
        allowNull: false
    },
    totalTime: {
        type: DataTypes.DOUBLE,
        allowNull: false
    },
    servings: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    rating: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
    notes: {
        type: DataTypes.STRING, allowNull: true
    },
}, {
    // Other model options go here
    tableName: 'Recipes'
});

export const Tag = sequelize.define('Tag', {
    // Model attributes are defined here
    name: {
        type: DataTypes.STRING,
        allowNull: false
    },
}, {
    // Other model options go here
    tableName: 'Tags'
});

export const RecipeTag = sequelize.define('RecipeTag', {
    // Model attributes are defined here
}, {
    // Other model options go here
    timestamps: false,
    tableName: 'RecipeTags'
});

這是我的協會:

Recipe.belongsToMany(Tag, {
    through: RecipeTag,
    foreignKey: 'recipeId',
    as: 'tags'
})

Tag.belongsToMany(Recipe, {
    through: RecipeTag,
    foreignKey: 'tagId',
    as: 'recipes'
})

這是創建調用:

Recipe.create(args, {
                model: Tag,
                through: RecipeTag,
                as: 'tags'
            });

這是數據:

{
  "title": "Test Recipe",
  "image": "test",
  "prepTime": 20,
  "cookTime": 40,
  "totalTime": 60,
  "servings": 2,
  "rating": 5,
  "categoryId": 1,
  "tags": [
    {
      "name": "New tag",
      "id": 1
    }
  ],
}

通過此設置,創建方法僅創建一個新配方。 如何在創建新食譜的同時使用 create 方法將記錄添加到加入的 RecipeTags 表中? 我已經設法通過做這樣的事情來讓它工作:

args.tags.map(async (tag: { tagId: number }) => {
    await RecipeTag.create({tagId: tag.tagId, recipeId: recipe.id})
});

但如果可能的話,我寧願在創建時完成它。

您需要使用include包裝關聯選項。

Recipe.create(args, {
    include: {
        model: Tag,
        through: RecipeTag,
        as: 'tags'
    }
});

更新:

為了防止重復,您可以添加ignoreDuplicates選項,數據必須包含主鍵值。

{
  "title": "Test Recipe",
  ...
  "tags": [
    {
      "name": "New tag",
      "id": 1   # this is important
    }
  ]
}

然后

Recipe.create(args, {
    include: {
        model: Tag,
        through: RecipeTag,
        as: 'tags',
        ignoreDuplicates: true  // Add this
    }
});

這個選項有一些錯誤,如果你最近沒有更新,我建議你使用更新版本的 Sequelize。

暫無
暫無

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

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