TransWikia.com

Objection.js add data from joined table to parent json

Stack Overflow Asked by iDaniel19 on November 2, 2020

I have the following Objection.js models:

Appointment:

'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

AppointmentType:

'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

Using the following query:

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

I get the following results:

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

In most cases, the default return from objection is useful but in this one not so much. Would it be possible to return something like:

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

I think this is not possible yet. I ll just parse the object again, or use it just like that. I’ll leave this here in case someone has found a nice way

One Answer

you can select the columns you want and they'll return as one flat object

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

but this is vulnerable to duplicates only if an appointment has many types. be careful

Answered by Abed Murrar on November 2, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP