fix: get association model by field target

This commit is contained in:
chenos 2020-12-25 16:13:33 +08:00
parent 76acd162e4
commit 32774657d7

View File

@ -36,8 +36,13 @@ export async function list(ctx: Context, next: Next) {
resourceName, resourceName,
resourceField, resourceField,
} = ctx.action.params; } = ctx.action.params;
const Model = ctx.db.getModel(resourceName); let data = {};
const options = Model.parseApiJson({ let options: any = {};
let Model;
if (associated && resourceField) {
const AssociatedModel = ctx.db.getModel(associatedName);
Model = ctx.db.getModel(resourceField.options.target);
options = Model.parseApiJson({
sort, sort,
page, page,
perPage, perPage,
@ -45,9 +50,6 @@ export async function list(ctx: Context, next: Next) {
fields, fields,
context: ctx, context: ctx,
}); });
let data = {};
if (associated && resourceField) {
const AssociatedModel = ctx.db.getModel(associatedName);
if (!(associated instanceof AssociatedModel)) { if (!(associated instanceof AssociatedModel)) {
throw new Error(`${associatedName} associated model invalid`); throw new Error(`${associatedName} associated model invalid`);
} }
@ -77,6 +79,15 @@ export async function list(ctx: Context, next: Next) {
count, count,
}; };
} else { } else {
Model = ctx.db.getModel(resourceName);
options = Model.parseApiJson({
sort,
page,
perPage,
filter,
fields,
context: ctx,
});
data = await Model.scope(options.scopes||[]).findAndCountAll({ data = await Model.scope(options.scopes||[]).findAndCountAll({
...options, ...options,
// @ts-ignore hooks 里添加 context // @ts-ignore hooks 里添加 context