简体   繁体   中英

How can i search by field of joined table in graphql and nestjs

i create two table tag and tagTranslation. following is field of each

Tag
id, type, transloations, creaed_at, updated_at

TagTranslation
id, tag_id, name, language

I use graphql, i want to get tag list by type, name and language

{ tags(name:"tag1", language:"en, type:3){
    id,
    type,
    translations{
      id,
      name,
      language,
    }
}
}

so I create resolver like following

@Query(returns => [Tag])
tags(@Args() tagArgs: TagArgs): Promise<Tag[]> {

    const where = {
        ...(tagArgs.type) && {type: tagArgs.type}
    };

    const include_where = {
        ...(tagArgs.name) && {name: { [Op.like]: `%${tagArgs.name}%` }},
        ...(tagArgs.language) && {language: tagArgs.language}
    };

    return this.tagService.findAll({
        where: where,
        include: {
            as: 'translations',
            model: TagTranslation,
            where: include_where,
            required: true,
        }
    });
}

@Query(returns => Tag)
tag(@Args({name: 'id', type: ()=> Int}) id: number): Promise<Tag>{
    return this.tagService.get(id)
}

@ResolveProperty()
async translations(@Parent() tag): Promise<TagTranslation[]>{
    const { id } = tag;
    return await this.tagTranslationService.findAll({tag_id: id});

}

when i call tags, the query is called twice

first, A query is executed to get the results I want.

but second,

SELECT `id`, `tag_id`, `name`, `language`, `created_at`, `updated_at` FROM `tag_translation` AS `TagTranslation` WHERE `TagTranslation`.`tag_id` = 1;

query is called once more, so i can't get results what i want.

I think second query is called because of ResolveProperty, I remove ResolveProperty. after that, tag query is not include tagtranslation info...

how can i solve that problem? or is there another idea??

how can i solve that problem? or is there another idea??

Relations between entities should be resolved on a field resolver ( @ResolveProperty() ) level because when someone requests only id and type , you will still perform additional, not needed join on TagTranslation in sql query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM