sequelize 一对多 多对多

/*
 * @Description: 
 * @Author: 熊成强
 * @Date: 2019-07-29 11:47:34
 * @LastEditTime: 2019-08-02 11:03:06
 * @LastEditors: 熊成强
 */
var express = require('express');
var forToken = require('../token');
var router = express.Router();
const users = require('../server/User.js')
const mode = require('../server/index.js')
const sequelize = require('sequelize');
const cache = require('../redis')



var log = require('log4js').getLogger("index");

/* GET users listing. */
// 多对多
router.get('/', function (req, res, next) {
  mode.User.findAll({
    raw: false,
    attributes: ['user_name'],
    where: {
      // teacher_name: "张老师"
    },
    include: [{
      model: mode.Teacher,
      attributes: [
        'teacher_name'
      ],
      through: { //除去中间表
        attributes: []
      },
      where: {
        teacher_name: {
          [sequelize.Op.like]: '张%'
        }
      }
    }]
  }).then(r => {
    console.log(r)
    res.send({
      code: '200',
      data: {
        code: '200',
        data: r
      }
    })
  })


  // return
  //一对多  
  // mode.School.findAll({
  //   raw: false,
  //   attributes: ['school_name'],
  //   include: [{
  //     model: mode.User,
  //     attributes: ['user_name'],
  //     where: {
  //       user_name: {
  //         [sequelize.Op.like]: '%1%'
  //       }
  //     }
  //   }]
  // }).then(r => {
  //   console.log(r)
  //   res.send({
  //     code: '200',
  //     data: {
  //       code: '200',
  //       data: r
  //     }
  //   })
  // })

});





module.exports = router;

/*
 * @Description: 
 * @Author: 熊成强
 * @Date: 2019-07-29 11:47:34
 * @LastEditTime: 2019-08-02 11:05:10
 * @LastEditors: 熊成强
 */
var fs = require('fs');

const mode = {}
fs.readdirSync(__dirname).filter((value) => {

  return value !== 'index.js'; //过滤自身

}).map(value => mode[value.split('.')[0]] = require('./' + value));

console.log(mode)
//为用户和学校建立关系  一对多
mode.School.hasMany(mode.User, {
  foreignKey: 'school_id',
  sourceKey: 'id',
  constraints: false
})

mode.User.belongsTo(mode.School, {
  foreignKey: 'school_id',
  targetKey: 'id',
  constraints: false
})

//多对多
mode.Teacher.belongsToMany(mode.User, {
  through: mode.TeachToUser,
  foreignKey: 'teacher_id',
  constraints: false
})
mode.User.belongsToMany(mode.Teacher, {
  through: mode.TeachToUser,
  foreignKey: 'user_id',
  constraints: false
})

module.exports = mode;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值