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
from Objection.js add data from joined table to parent json
No comments:
Post a Comment