sequelize模型关联_egg-sequelize关联查询两种方法

两张表,博客(blog_content)和分类(blog_type)

blog_content表,包含id,title,content,type_id字段,其中type_id指向blog_type表中的id

blog_type表,包含id,type_name字段

想要查询博客列表时,查询到分类名字

定义模型如下:

//blog模型

module.exports = (app) => {

const { STRING, INTEGER,DATE,Now } = app.Sequelize;

const Blog = app.model.define(

"blog",

{

id: {

type: INTEGER,

primaryKey: true,

autoIncrement: true,

},

title:STRING,

content: STRING,

type_id:INTEGER,

},

{

timestamps: false,

freezeTableName: true,

tableName: "blog_content"

}

);

return Blog;

};

//type模型

module.exports = (app) => {

const { STRING, INTEGER } = app.Sequelize;

const Type = app.model.define(

"type",

{

id: {

type: INTEGER,

primaryKey: true,

autoIncrement: true,

},

type_name:STRING,

},

{

timestamps: false,

freezeTableName: true,

tableName: "blog_type"

}

);

return Type;

};

1.第一种查询方式,在service里面定义关联方式,然后直接查询,如下

const Service = require('egg').Service;

class BlogService extends Service {

async list() {

let blogModel = this.ctx.model.Blog;

let typeModel = this.ctx.model.Type;

//下面是重点,blogModel的type_id,指向typeModel的id

blogModel.belongsTo(typeModel, {

foreginkey: "type_id",

targetkey: "id",

})

let result = await blogModel.findAll({

include: [{ model: typeModel, attributes: ['type_name'] }]

})

return result

}

}

module.exports = BlogService;

2.第二种,在模型里直接定义属于关系,查询时候直接查询,如下

//修改blog模型,在return Blog之前加上如下方法

Blog.associate = function() {

app.model.Blog.belongsTo(app.model.Type, { foreignKey: 'type_id', targetKey: 'id'})

}

//service 查询方式也简化如下

async list() {

let result = await this.ctx.model.Blog.findAll({

include: [{ model: this.ctx.model.Type, attributes: ['type_name'] }]

})

return result

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值