Sequelize关联表

关联表

示例:现在要关联两张表:system 跟 user_sytem,

model
'use strict';

module.exports = app => {
  const { STRING, DATE, INTEGER } = app.Sequelize;
  const system = app.model.define('system_info',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      system_id: { type: STRING },
      name: { type: STRING },
      description: { type: STRING },
      token: { type: STRING },
      created_time: { type: DATE },
    },
    {
      freezeTableName: true,
      timestamps: false,
    });
  system.associate = () => { // 建立关联
    system.hasOne(app.model.UserSystem, {
      foreignKey: 'id', // 在 UserSystem 的外键名称
      constraints: false, // 这个属性非常重要,可以用来表示这个关联关系是否采用外键关联。在大多数情况下我们是不需要通过外键来进行数据表的物理关联的,直接通过逻辑进行关联即可;
    });
  };
  return system;
};
'use strict';

module.exports = app => {
  const { STRING, INTEGER } = app.Sequelize;
  const userSystem = app.model.define('user_system',
    {
      uid: { type: STRING, primaryKey: true },
      id: { type: INTEGER, primaryKey: true },
      system_id: { type: STRING, primaryKey: true },
    },
    {
      freezeTableName: true,
      timestamps: false,
    });
  return userSystem;
};

service:

进行查询

const systems = await ctx.model.System.findAndCountAll({
    attributes: [ 'id', 'name', 'description', 'created_time' ],
    limit,
    offset,
    include: [{
        model: ctx.model.UserSystem,
        attributes: [], // 一定需要的,不然select的列会包含进去
        where: { uid },
    }],
});

执行原始SQL,防注入

const sequelize = require('sequelize');
const sql = `select * from user where id = ? and age>?`;
await ctx.model.query(sql,
                     { replacements: [1,18],type: sequelize.QueryTypes.SELECT });
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值