在sequelize中将关联的表属性作为主表属性传递

时间:2019-06-05 04:38:11

标签: mysql node.js database express sequelize.js

我有一个与以下查询类似的查询。

const TODAY = new Date().setHours(0, 0, 0, 0);
const studentAttendances = await STUDENT_ATTENDANCES.findAll({
  where: {
    punch_in: { [Op.gt]: TODAY },
  },
  attributes: ['id', 'student_id', 'arrived_time'],
  include: [
    {
      model: STUDENTS,
      attributes: ['name'],
    },
  ],
  raw: true,
  nest: true,
});

给出的当前输出是一个对象数组,如下所示。

 {
        "id": 1041,
        "student_id": 16,
        "arrived_time": "2019-05-29T08:29:41.000Z",
        "student": {
            "name": "Tom"
        }
    },

我不是像上面那样嵌套对象,而是如何使学生姓名本身成为主要对象的属性?示例如下。

   {
        "id": 1041,
        "student_id": 16,
        "arrived_time": "2019-05-29T08:29:41.000Z",
        "student": "Tom"
    },
  

我希望通过使用任何 JS 循环而无需续集来实现此目的

2 个答案:

答案 0 :(得分:0)

我认为您可以使用纯JavaScript来处理它:

studentAttendances = studentAttendances.get({plain: true})

for(student in studentAttendances){
  studentAttendances[student].student = studentAttendances[student].student.name
}

答案 1 :(得分:0)

假设您的单一模型名称为“学生”,则类似的事情应该起作用:

 const studentAttendances = await STUDENT_ATTENDANCES.findAll({
  where: {
    punch_in: { [Op.gt]: TODAY },
  },
  attributes: [
    [sequelize.col('Student.name'), 'studentName'], // will give you name as 'studentName'
    'id', 'student_id', 'arrived_time'
  ],
  include: [
    {
      model: STUDENTS,
      attributes: [], // empty this out 
    },
  ]
});