Sequelize实现一对多关联

作者: adm 分类: node 发布时间: 2022-07-06

模型一

const Sequelize = require('sequelize')
const moment = require('moment')
const sequelize = require('./init')
const tools = require('../utils/tools')
const CargoOrderModel=require('./orderDetail')


// 定义表的模型
const CargoOrderCommonModel = sequelize.define('export_cargo_order_common', {
  id: {
    type: Sequelize.STRING(36),
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: Sequelize.STRING(32),
  },
  order_type: {
    type: Sequelize.STRING(32)
  },
  order_no: {
    type: Sequelize.STRING(32)
  },
  status: {
    type: Sequelize.TINYINT(4),
    defaultValue: 0
  },
  update_time: {
    type: Sequelize.DATE,
    get() {
      return this.getDataValue('update_time') ? moment(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss') : null
    }
  },
  create_time: {
    type: Sequelize.DATE,
    defaultValue: Sequelize.NOW,
    get() {
      return moment(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss')
    }
  }
},
  {
    // 告诉 sequelize 不需要自动将表名变成复数
    freezeTableName: true,
    // 自定义表名
    // tableName: 'student',
    // 不需要自动创建 createAt / updateAt 这两个字段
    timestamps: false,
   /*  // 指定索引
    indexes: [
        {
            // 索引名称
            name: 'idx_age',
            // 索引字段名称
            fields: ['age'],
        }
    ] */

});

CargoOrderCommonModel.hasMany(CargoOrderModel, {
  foreignKey: 'order_no',
   sourceKey: 'order_no'
})
//CargoOrderModel.belongsTo(CargoOrderCommonModel);

module.exports = CargoOrderCommonModel

模型二

const Sequelize = require('sequelize')
const moment = require('moment')
const sequelize = require('./init')
const tools = require('../utils/tools')



// 定义表的模型
const CargoOrderModel = sequelize.define('detail', {
  
  order_no: {
    type: Sequelize.STRING(32)
  },
  cupboard: {
    type: Sequelize.STRING(32)
  },
  cupboard_num: {
    type: Sequelize.STRING(4),
    defaultValue: 0
  },
  
},
  {
    // 告诉 sequelize 不需要自动将表名变成复数
    freezeTableName: true,
    // 自定义表名
     tableName: 'export_cargo_order',
    // 不需要自动创建 createAt / updateAt 这两个字段
    timestamps: false,
   /*  // 指定索引
    indexes: [
        {
            // 索引名称
            name: 'idx_age',
            // 索引字段名称
            fields: ['age'],
        }
    ] */

});



module.exports = CargoOrderModel

router

const express = require('express')
const router = express.Router()




const OrderController = require('../controller/order');
const orderController = new OrderController();

router.post("/list", orderController.getOrderList)

controller

 const express = require('express');

const OrderService = require('../service/order');
const orderService = new OrderService();
const Sequelize = require('sequelize')
const Op = Sequelize.Op

class OrderController {
    async getOrderList(req, res) {
        let where = {}

        if (req.body.pick_up_time_begin && req.body.pick_up_time_end) {
            where = {
            pick_up_time: {
                [Op.between]: [req.body.pick_up_time_begin,req.body.pick_up_time_end]
            }
            }
        }
        const resp = await orderService.getOrderList(where, function (callback) {
            
            for (var i=0;i<callback.length;i++)
            { 
              let cupboard='';
              //console.log(callback[i].dataValues)
              for (var j=0;j<callback[i].dataValues.details.length;j++){
                cupboard+=callback[i].dataValues.details[j].cupboard+"*"+callback[i].dataValues.details[j].cupboard_num+'\r\n'
                
              }
            
              callback[i].dataValues.cupboards=cupboard
            
            } 
            res.send({
                code: 200,
                msg: "请求数据成功",
                data: callback
            })

        })



    }

    

   
}

module.exports = OrderController;

service



    const CargoOrderCommonModel = require('../model/order')
    const CargoOrderModel=require('../model/orderDetail')

class OrderService {
    async getOrderList(where,callback) {
         CargoOrderCommonModel.findAndCountAll({
    
            //offset,
            //limit: parseInt(req.query.limit) || 20,
             include: [
              {
                model: CargoOrderModel,
                attributes: ['cupboard','cupboard_num']
              }
            ], 
            where: where,
            order: [['create_time', 'DESC']]
          }).then(function(result) {
            callback(result.rows)
            return 
        
        })
        


    }

    
}
module.exports = OrderService;

查询结果

{
    "code": 20000,
    "message": "获取成功",
    "data": {
        "record": [
            {
                "update_time": "2022-06-07 10:09:29",
                "create_time": "2022-06-07 10:09:29",
                "id": "1654567769000000257",
                "user_id": "20",
                "order_type": "铁路订单",
                "order_no": "92022060710092975210",
                "status": 1,
                "details": [
                    {
                        "cupboard": "20GP",
                        "cupboard_num": "15"
                    },
                    {
                        "cupboard": "",
                        "cupboard_num": "0"
                    },
                    {
                        "cupboard": "40GP",
                        "cupboard_num": "3"
                    }
                ]
            }
        ],
        "total": 1
    }
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!