【问题标题】:Passing associated table attributes as main table attributes in sequelize在 sequelize 中将关联的表属性作为主表属性传递
【发布时间】:2019-10-20 14:24:10
【问题描述】:

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

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 循环来完成此操作

【问题讨论】:

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


    【解决方案1】:

    假设您的单数模型名称是“学生”,这样的事情应该可以工作:

     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 
        },
      ]
    });
    

    【讨论】:

      【解决方案2】:

      我认为你可以用纯 javascript 处理它:

      studentAttendances = studentAttendances.get({plain: true})
      
      for(student in studentAttendances){
        studentAttendances[student].student = studentAttendances[student].student.name
      }
      

      【讨论】:

      • 感谢您的回答。我希望直接通过 sequelize 找到解决方案,而不使用循环。我编辑了问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      相关资源
      最近更新 更多