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)
}
})
希望大家能指点下
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在models/ArticleTag.js(文章标签关联)关联的model中修改这部分的代码
修改为下面的代码