H5W3
当前位置:H5W3 > 问答 > 正文

sequelize多对多关联

sequelize多对多关联查不到关联数据

一个文章关联多个标签,Article对应多个Tag,Tag也可以对应多个Article

相关代码

// models/index.js (做统一的导出模块)
const { DataTypes } = require('sequelize')
const sequelize = require('../plugins/mysql')
module.exports = {
Article: require('./Article')(sequelize, DataTypes),
Tag: require('./Tag')(sequelize, DataTypes),
ArticleTag: require('./ArticleTag')(sequelize, DataTypes),
}
// models/Article.js
module.exports = (sequelize, DataTypes) => {
const Article = sequelize.define(
'Article',
{
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true,
},
articleTitle: {
type: DataTypes.STRING,
comment: '文章标题',
},
articleIntroduction: {
type: DataTypes.STRING(300),
comment: '文章简介',
},
articleCoverImage: {
type: DataTypes.STRING(500),
comment: '封面图',
},
articleBackgroundImage: {
type: DataTypes.STRING(500),
comment: '背景',
},
articleMarkdown: {
type: DataTypes.TEXT('tiny'),
comment: '文章内容(MD)',
},
articleClickNumber: {
type: DataTypes.BIGINT,
comment: '点击数',
defaultValue: 0,
},
articleSort: {
type: DataTypes.BIGINT,
comment: '排序',
defaultValue: 0,
},
},
{
comment: '文章',
}
)
return Article
}
// models/Tag.js
module.exports = (sequelize, DataTypes) => {
const Tag = sequelize.define(
'Tag',
{
tagName: {
type: DataTypes.STRING,
comment: '标签名称',
},
tagIntroduce: {
type: DataTypes.STRING(300),
comment: '标签简介',
},
tagStatus: {
type: DataTypes.ENUM('1', '2'),
comment: '标签状态',
},
tagClickNumber: {
type: DataTypes.BIGINT,
defaultValue: 0,
comment: '点击数',
},
tagSort: {
type: DataTypes.BIGINT,
defaultValue: 0,
comment: '排序',
},
},
{
comment: '标签',
}
)
return Tag
}
// models/ArticleTag.js(文章标签关联)
module.exports = (sequelize, DataTypes) => {
const Article = require('./Article')(sequelize, DataTypes)
const Tag = require('./Tag')(sequelize, DataTypes)
const ArticleTag = sequelize.define(
'ArticleTag',
{
tagId: {
type: DataTypes.INTEGER,
references: {
model: Tag,
key: 'id',
},
},
articleId: {
type: DataTypes.INTEGER,
references: {
model: Article,
key: 'id',
},
},
},
{
comment: '文章标签关联',
}
)
Article.belongsToMany(Tag, {
through: 'ArticleTag',
foreignKey: 'tagId',
sourceKey: 'id',
})
Tag.belongsToMany(Article, {
through: 'ArticleTag',
foreignKey: 'articleId',
sourceKey: 'id',
})
return ArticleTag
}
  //接口部分
router.post('/', async (req, res, next) => {
try {
const ArticleRes = await Article.create(req.body)
console.log(ArticleRes)
// ArticleRes里面并没有getTag,setTag这样的方法
res.response(200, '添加成功', ArticleRes)
} catch (error) {
console.log(error)
next(error)
}
})

希望大家能指点下

在models/ArticleTag.js(文章标签关联)关联的model中修改这部分的代码

 Article.belongsToMany(Tag, {
through: 'ArticleTag',
foreignKey: 'tagId',
sourceKey: 'id',
})
Tag.belongsToMany(Article, {
through: 'ArticleTag',
foreignKey: 'articleId',
sourceKey: 'id',
})

修改为下面的代码

 ArticleTag.belongsTo(Tag, {
foreignKey: 'tagId',
constraints: false,
})
ArticleTag.belongsTo(Article, {
foreignKey: 'articleId',
constraints: false,
})

回答

本文地址:H5W3 » sequelize多对多关联

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址