例如现在有一张文章表article,category_id 代表的是文章的分类,另一张tags表存储的是文章的分类名称,两者的关系是article中的category_id与tags中的id关联,如何根据category_id获取到tags中的分类名称
Tags表:
Tag.init({ id: { type: Sequelize.INTEGER, primaryKey: true,//设置主键 autoIncrement: true,//自增长 }, tag_name: { type: Sequelize.STRING, unique: true, validate: { notEmpty: { msg: "标签名不能为空" } } }, }, { sequelize, tableName: 'tags' })
article表:
ArticleModel.init({ id: { type: Sequelize.INTEGER, primaryKey: true,//设置主键 autoIncrement: true,//自增长 }, title: { type: Sequelize.STRING, require: true }, top: { type: Sequelize.BOOLEAN, }, category_id: { type: Sequelize.INTEGER, require: true }, keyword: Sequelize.STRING, thumb_url: Sequelize.STRING, desc: { type: Sequelize.STRING, require: true }, content: Sequelize.TEXT, article_author: Sequelize.STRING, count: { type: Sequelize.INTEGER, defaultValue: 0 } }, { sequelize, tableName: 'article' })
关联查询:
ArticleModel.belongsTo(关联的模型, { foreignKey: '使用什么字段关联', targetKey: '与关联的模型那个字段关联', as: '别名' }); ArticleModel.belongsTo(Tag, { foreignKey: 'category_id', targetKey: 'id', as: 'tag_category' });
大白话翻译就是 Article需要与tag模型关联,根据articleModel的categoty_id和Tag中的id关联
关联查询:
static async findAllArticle(page, size) { try { let tagInfo = await ArticleModel.findAndCountAll({ limit: Number(size), offset: Number(size * (page - 1)), order: [ ['createdAt', 'DESC'] ], include: [{ model: Tag, as: 'tag_category',//这里的 as需要与之前定义的as名字相同 }] }) return { code: 0, message: tagInfo } } catch (e) { return { code: -1, message: e } } }
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接