【问题标题】:Sequelize Model.create with many-to-many associationsSequelize Model.create 与多对多关联
【发布时间】:2020-03-17 15:22:27
【问题描述】:

我建立帖子和标签模型。

帖子属于很多标签,标签也属于很多帖子。

当我创建一些带有标签的帖子时,会出现 KEY DUPLICATE 错误。

如果这种方式不对,如何创建带有标签的帖子?

谢谢。

nodejs:v13.10.1

续集(使用mysql2):^5.21.5

mysql2: ^2.1.0

数据库(在 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))

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    我想这个关联对你的情况来说已经足够了:

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

    【讨论】:

    • 谢谢。我意识到如果我想这样做,我必须创建标签 1、2 和 3(通过 findOrCreate),然后将它们添加到帖子中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2014-04-15
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多