首页 > 解决方案 > Objection.js 将数据从连接表添加到父 json

问题描述

我有以下 Objection.js 模型:

预约:

'use strict'

const { Model } = require('objection')

class Appointment extends Model {
  // Table name is the only required property.
  static get tableName() {
    return 'appointment'
  }

  static get idColumn() {
    return 'appointmentId';
  }

   // This object defines the relations to other models.
   static get relationMappings() {
    // One way to prevent circular references
    // is to require the model classes here.
    const AppointmentType = require('./AppointmentType')

    return {
      appointmentType: {
        relation: Model.BelongsToOneRelation,
        // The related model. This can be either a Model subclass constructor or an
        // absolute file path to a module that exports one.
        modelClass: AppointmentType,
        join: {
          from: 'appointment.appointmentTypeId',
          to: 'appointmentType.appointmentTypeId'
        }
      },
    }
  }
}

module.exports = Appointment

约会类型:

'use strict'

const { Model } = require('objection')

class AppointmentType extends Model {
  // Table name is the only required property.
  static get tableName() {
    return 'appointmentType'
  }

  static get idColumn() {
    return 'appointmentTypeId';
  }
}

module.exports = AppointmentType

使用以下查询:

await Appointment.query().withGraphJoined({appointmentType: true})

我得到以下结果:

   {
        "appointmentId": 1,
        "duration": 12,
        "appointmentTypeId": 2,
        "appointmentType": {
            "appointmentTypeId": 2,
            "appointmentTypeName": "Type Name"
        }
    ....
    }

在大多数情况下,反对的默认返回是有用的,但在这一个中没有那么多。是否有可能返回类似的东西:

  {
        "appointmentId": 1,
        "duration": 12,
        "appointmentTypeName": "Type Name" // or "typeName": "Type Name"
        ...
    }

我认为这还不可能。我将再次解析该对象,或者就这样使用它。我会把这个留在这里,以防有人找到一个好方法

标签: node.jsknex.jsobjection.js

解决方案


您可以选择所需的列,它们将作为一个平面对象返回

const appointments = await Appointment.query().select('appointmentId','duration', 'appointmentTypeName').leftJoinRelated('appointmentType');

但这只有在约会有多种类型时才容易受到重复的影响。当心


推荐阅读