简体   繁体   English

使用多对多关联对 Model.create 进行后续处理

[英]Sequelize Model.create with many-to-many associations

I build posts and tags model.我建立帖子和标签模型。

Post belongs to many tags and tags belongs to many posts too.帖子属于许多标签,标签也属于许多帖子。

When I create few posts with tags, it occurs KEY DUPLICATE error.当我创建几个带有标签的帖子时,会出现 KEY DUPLICATE 错误。

If this way is wrong, how can I create a post with tags?如果这种方式是错误的,我如何创建带有标签的帖子?

Thanks.谢谢。

nodejs: v13.10.1 nodejs: v13.10.1

sequelize(with mysql2): ^5.21.5续集(使用 mysql2):^5.21.5

mysql2: ^2.1.0 mysql2: ^2.1.0

database(on Amazon RDS): MariaDB 10.2.21数据库(在 Amazon RDS 上):MariaDB 10.2.21

require('dotenv').config()
const Sequelize = require('sequelize')

const host = process.env.DB_HOST
const database = process.env.DB_NAME
const username = process.env.DB_USERNAME
const password = process.env.DB_PASSWORD

const sequelize = new Sequelize(database, username, password, {
  host: host,
  dialect: 'mysql'
})

const Model = Sequelize.Model
const DataTypes = Sequelize.DataTypes

class Post extends Model {}

Post.init({
  title: { type: DataTypes.STRING }
}, { sequelize, modelName: 'post' })

class Tag extends Model {}

Tag.init({
  value: { type: DataTypes.STRING }
}, { sequelize, modelName: 'tag' })

Post.belongsToMany(Tag, { as: 'tags', through: 'post_tags' })
Tag.belongsToMany(Post, { as: 'posts', through: 'post_tags' })

async function main () {
  await sequelize.sync({ force: true })
  const post1 = await Post.create({
    title: 'title1',
    tags: [
      { id: 1, value: 'tag1' },
      { id: 2, value: 'tag2' }
    ]
  }, {
    include: [
      {
        model: Tag,
        as: 'tags'
      }
    ]
  })

  const post2 = await Post.create({
    title: 'title2',
    tags: [
      { id: 1, value: 'tag1' }, // Duplicate entry '1' for key 'PRIMARY'
      { id: 3, value: 'tag3' }
    ]
  }, {
    include: [
      {
        model: Tag,
        as: 'tags'
      }
    ]
  })

  const r = await Post.findAll({
    include: [
      {
        model: Tag,
        as: 'tags'
      }
    ]
  })

  console.log(r)
}

main()
  .catch((err) => console.error(err))

I guess that this association will be enough for your case:我想这个关联对于你的情况就足够了:

Post.hasMany(Tag, { as: 'tags' })
Tag.belongsToMany(Post, { as: 'postTags', through: 'post_tags' })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM