node.js - 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"
...
}
我认为这还不可能。我将再次解析该对象,或者就这样使用它。我会把这个留在这里,以防有人找到一个好方法
解决方案
您可以选择所需的列,它们将作为一个平面对象返回
const appointments = await Appointment.query().select('appointmentId','duration', 'appointmentTypeName').leftJoinRelated('appointmentType');
但这只有在约会有多种类型时才容易受到重复的影响。当心
推荐阅读
- maven - 使 Maven 输出仅显示已进行的子模块
- charts - 如何在 HIghcharts 的面积图中实现异步下钻?
- typescript - 使用斜线参数“/”调用 Api
- bitbucket - 由于身份验证问题,Sourcetree 无法推送到 bitbucket 存储库
- c# - 找不到类型或命名空间名称“HttpResponseMessage”
- django - heroku python 应用程序中没有名为“pyrebase”的模块
- node.js - RSYNCWRAPPER:rsync 以代码 12 退出
- spring - Spring Batch ResourcelessTransactionManager 与persistence.xml 混淆?
- javascript - Node.js mongoose 连接错误
- python - pandas:将所有具有 2 个值的列转换为 True/False