码迷,mamicode.com
首页 > Web开发 > 详细

egg.js两个表相互关联怎么写

时间:2020-07-06 19:56:33      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:syn   ram   关联   use   time   mit   EDA   hasone   model   

有两个表,第一个接口:如果a表是主表,需要连接多个表,其中有个是b表,另一个接口,b表是主表,需要连接多个,其中有个是a表,那么这时候在model里面不需要做2次关联,直接1次关联,然后直接在service里面的include去用这个关联名字就可以了,例如:
在HxUserBaseInfo表里面

this.belongsTo(app.model.HxUser, { foreignKey: ‘userId‘, targetKey: ‘userId‘, as: ‘basic‘ })

在HxUser表里面

this.hasOne(app.model.HxUserBaseInfo, { foreignKey: ‘userId‘, sourceKey: ‘userId‘, as: ‘basic‘ })

HxUserBaseInfo为主表的时候

async baseInfoById(userId) {
    const { rows } = await this.ctx.model.xxxxxxx.findAndCountAll({
      attributes: { exclude: [ ‘createdAt‘, ‘updatedAt‘ ] },
      where: {
        userId,
      },
      include: [
        {
          model: this.app.model.HxUser,
          as: ‘basic‘,
        },
      ],
    })
    return { list: rows }
  }
}

HxUser为主表的时候

 async userList({ limit, offset, userName = ‘‘, time, ...params }) {
    const { Op } = this.app.Sequelize
    const { rows, count } = await this.ctx.model.HxUser.findAndCountAll({
      attributes: { exclude: [ ‘createdAt‘, ‘updatedAt‘ ] },
      distinct: true,
      where: {
        ...time,
        ...params,
      },
      // 如果没有设置required: false的话 是inner 连接,如果设置了就是左连接
      include: [{
        model: this.app.model.HxUserBaseInfo,
        as: ‘basic‘,
        attributes: [ ‘userAvator‘, ‘userName‘, ‘gender‘ ],
        required: !!userName,
        where: {
          userName: {
            [Op.like]: `%${userName}%`,
          },
        },
      },
      ],
      offset,
      limit,
    })
    return { list: rows, total: count }
  }

egg.js两个表相互关联怎么写

标签:syn   ram   关联   use   time   mit   EDA   hasone   model   

原文地址:https://www.cnblogs.com/antyhouse/p/13256337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!