简体   繁体   中英

Optional Property in TypeORM FindOptionsWhere

I am trying to fetch translations for different types of questions from my database. The problem is, that some questions have options, some do not.

    const where: FindOptionsWhere<QuestionTranslation> = {
      question: {
        // some other props
        options: { // this needs to be optional
          translations: {
            lang: In([localeCode, baseLocaleCode, LocaleCode.en]),
          },
        },
      },
    };

    const questionTranslations = await this.questionTranslationRepository.find({
      where,
    });

If I remove the options property, I get all translations, but the translations for options are obviously missing on questions that have them. If I include it, questions without options are left out.

I want to avoid having to call the database twice (with FindOptionsWhere object that includes or excludes the options property respectively). Something like this would be nice:

        options: {
          [if exists]: {
            translations: {
              lang: In([localeCode, baseLocaleCode, LocaleCode.en]),
            },
          },
        },

Is this possible?

Try with the following approach.

Wrapping the where -clause in an array, will translate to an OR condition in SQL .

import { IsNull } from "typeorm";

const questionTranslations = await this.questionTranslationRepository.find({
  where: [
    { question: { options: IsNull() } },
    { question: {
      options: {
        translations: {
          lang: In([localeCode, baseLocaleCode, LocaleCode.en]),
        },
      },
    }}
  ],
});

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