我使用PostgreSQL和objection.js进行ORM。当我使用$relatedQuery方法时,我得到QueryBuilder个对象而不是模型实体。
Here是示例项目以及如何使用$relatedQuery
方法。
podcastListener.js
const { Model, snakeCaseMappers } = require('objection');
class Podcast extends Model {
static get tableName() {
return 'podcasts_listeners';
}
static get columnNameMappers() {
return snakeCaseMappers();
}
static get jsonSchema() {
return {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string', minLength: 1, maxLength: 100 },
},
};
}
static get relationMappings() {
return {
usersRel: {
relation: Model.BelongsToOneRelation,
modelClass: `${__dirname}/user`,
join: {
from: 'podcasts_listeners.user_id',
to: 'users.id',
},
},
episodesRel: {
relation: Model.HasManyRelation,
modelClass: `${__dirname}/episode`,
join: {
from: 'podcasts_listeners.id',
to: 'episodes.podcasts_listeners_id',
},
},
};
}
}
module.exports = Podcast;
episode.js
const { Model, snakeCaseMappers } = require('objection');
class Episode extends Model {
static get tableName() {
return 'episodes';
}
static get columnNameMappers() {
return snakeCaseMappers();
}
static get jsonSchema() {
return {
type: 'object',
properties: {
podcasts_listeners_id: { type: 'integer' },
id: { type: 'integer' },
episode_name: { type: 'string', minLength: 1, maxLength: 100 }, },
description: { type: 'string' },
},
};
}
static get relationMappings() {
return {
podcastRel: {
relation: Model.BelongsToOneRelation,
modelClass: `${__dirname}/podcastListener`,
join: {
from: 'episodes.podcasts_listeners_id',
to: 'podcasts_listeners.id',
},
},
};
}
}
module.exports = Episode;
如果我跑:
const podcast = await PodcastListener.query()
.findOne('name', podcastName);
const episode = podcast
.$relatedQuery('episodesRel')
.findById(6);
或:
const episode = podcast
.$relatedQuery('episodesRel');
剧集变量为QueryBuilder
而不是Episode
模型。
答案 0 :(得分:1)
我失踪了await
:
const episode = await podcast
.$relatedQuery('episodesRel');