【发布时间】: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