Skip to content

[Question] QueryBuilder - Issues with executing a query builder. #747

Closed

Description

@popovicidinu

Hi all,

I'm getting the following error when using the QueryBuilder functionality.


[Nest] 6940   - 2017-8-8 12:14:18   [ExceptionsHandler] Cannot read property 'databaseName' of undefined
TypeError: Cannot read property 'databaseName' of undefined
    at /Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1220:91
    at Array.map (native)
    at SelectQueryBuilder.createOrderByCombinedWithSelectExpression (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1216:14)
    at SelectQueryBuilder.<anonymous> (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1130:35)
    at step (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:42:23)
    at Object.next (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:23:53)
    at /Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:17:71
    at Promise (<anonymous>)
    at __awaiter (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:13:12)
    at SelectQueryBuilder.executeEntitiesAndRawResults (/Users/iulian/Development/GitzioApi/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1106:16)

My side of the code:

1. Function that makes the query
 
 public async getPopular(): Promise<Industry[]>{
        return await (await this.repository).createQueryBuilder('industry')
            .orderBy('industry.counter', 'DESC')
            .take(10).getMany();
    }

2. The (await this.repository) part. 

 private get repository(): Promise<Repository<Industry>> {
        return this.databaseService.getRepository(Industry);
    }

3. The database service function that picks the repository.

 public async getRepository<T>(entityClassOrName: ObjectType<T> | string): Promise<Repository<T>> {
        return (await this.connection).getRepository<T>(entityClassOrName);
    }

It seems that the SelectQueryBuilder cannot fetch the column.databaseName (the name in the database for that column. The error seems to come from the entityMetadata section, as it didn't load the metadata correctly (or it cannot find it?).

Any thoughts would be nice. 👍

Activity

  1. popovicidinu commented on Aug 8, 2017

    @popovicidinu
    Author

    After some debugging it seems there's an error with the following lines of code:

    line 1220:   var column = alias.metadata.findColumnWithPropertyName(propertyPath);
    line 1231:   var column = alias.metadata.findColumnWithPropertyName(propertyPath);
    

    If I change that to: findColumnWithDatabaseName it seems to work and executes the query builder correctly.

    Is this is a bug in SelectQueryBuilder class, or a bug with the findColumnwithPropertyName() function from EntityMetadata ?

  2. pleerock commented on Aug 10, 2017

    @pleerock
    Member

    Please provide a minimal reproduction code without any boilerplate code. entity and few lines of code which reproduce this issue.

  3. popovicidinu commented on Aug 11, 2017

    @popovicidinu
    Author

    @pleerock Fixed this after testing my code again. You can close it off since this isn't a bug.

    Thanks for the help and the great work!!

  4. mentos1386 commented on Sep 17, 2017

    @mentos1386

    @popovicidinu hey, i'm having the same problem. How did you fix it?

  5. d-bechtel commented on Dec 4, 2017

    @d-bechtel

    i have the same error with this query:
    let query = this.activityRepository.createQueryBuilder('activity')
    .select()
    .addSelect('user.email as email')
    .innerJoinAndSelect('activity.user', 'user')
    .skip(0)
    .take(10)
    .orderBy('activity.end_date', 'DESC')
    .where('user.email = :email').setParameter('email', userProfile.email);
    let activities = await query.getMany();

    if i use .limit(10) instead of .take(10), it works, but query returns duplicates.
    if i remove the orderBy clause it works, too. So i think the bug exists in combination of take and orderBy.

  6. pleerock commented on Dec 6, 2017

    @pleerock
    Member

    @d-bechtel I need more info, create a failing test with issue reproduction so I can take alook

  7. RDeluxe commented on Jul 26, 2018

    @RDeluxe

    I'm encountering the same issue.

    I have a somewhat complex query to build (I want to be able to order by relations keys )

      protected constructQueryBuilder(
        searchFields: CompanyFilterDTO,
        options: FindManyOptions<CompanyEntity>,
      ) {
        let qb = this.repository.createQueryBuilder('company');
    
        if (options.skip != null) qb = qb.skip(options.skip);
        if (options.take != null) qb = qb.take(options.take);
    
        qb = qb
          .leftJoinAndSelect('company.account', 'account')
          .leftJoinAndSelect('account.profilePicture', 'profilePicture')
          .leftJoinAndSelect('company.incubator', 'incubator')
          .leftJoinAndSelect('company.features', 'features')
          .leftJoinAndSelect('company.founders', 'founders')
          .leftJoinAndSelect('founders.avatar', 'founderAvatar')
          .leftJoinAndSelect('company.activities', 'activities')
          .leftJoinAndSelect('company.pictures', 'pictures')
          .leftJoinAndSelect('pictures.photo', 'photo');
    
        if (searchFields.keywords) {
          const words = searchFields.keywords
            .trim()
            .toLowerCase()
            .split(' ');
    
          words.forEach((element: string) => {
            const data: { [index: string]: string } = {};
            data[element] = `%${element}%`;
    
            qb = qb
              .orWhere(`company.city ILIKE :${element}`, data)
              .orWhere(`company.zipcode ILIKE :${element}`, data)
              .orWhere(`company.phone ILIKE :${element}`, data)
              .orWhere(`company.country ILIKE :${element}`, data)
              .orWhere(`account.email ILIKE :${element}`, data)
              .orWhere(`company.name ILIKE :${element}`, data);
          });
        }
    
        if (searchFields.city) {
          qb = qb.andWhere(`company.city ILIKE :city`, { city: `%${searchFields.city}%` });
        }
    
        if (searchFields.zipcode) {
          qb = qb.andWhere(`company.zipcode ILIKE :zipcode`, { zipcode: `%${searchFields.zipcode}%` });
        }
    
        if (searchFields.phone) {
          qb = qb.andWhere(`company.phone ILIKE :phone`, { phone: `%${searchFields.phone}%` });
        }
    
        if (searchFields.isDelinquent != null) {
          qb = searchFields.isDelinquent
            ? qb.andWhere(`account."isDelinquant" IS TRUE`)
            : qb.andWhere(`account."isDelinquant" IS FALSE`);
        }
    
        if (searchFields.validated != null) {
          qb = searchFields.validated
            ? qb.andWhere(`company.validated IS TRUE`)
            : qb.andWhere(`company.validated IS FALSE`);
        }
    
        if (searchFields.subscriptionTypes) {
          qb = qb.andWhere(`account."currentSubscription" IN (:...typeList)`, {
            typeList: searchFields.subscriptionTypes,
          });
        }
    
        if (options.order != null) {
          for (const k in options.order) {
            if (options.order.hasOwnProperty(k)) {
              let opt = (options.order as { [key: string]: 'ASC' | 'DESC' | 1 | -1 | undefined })[k];
    
              if (opt === 1) {
                opt = 'ASC';
              } else if (opt === -1) {
                opt = 'DESC';
              }
    
              qb = qb.addOrderBy(`${qb.alias}."${k}"`, opt);
            }
          }
        }
    
        console.log(qb.getSql());
    
        return qb;
      }

    The SQL query is fine. But I have this error:

    TypeError: Cannot read property 'databaseName' of undefined
    [1] sonly-api   |     at /home/node/src/query-builder/SelectQueryBuilder.ts:1852:114
    [1] sonly-api   |     at Array.map (<anonymous>)
    [1] sonly-api   |     at SelectQueryBuilder.createOrderByCombinedWithSelectExpression (/home/node/src/query-builder/SelectQueryBuilder.ts:1847:14)
    [1] sonly-api   |     at SelectQueryBuilder.<anonymous> (/home/node/src/query-builder/SelectQueryBuilder.ts:1765:46)
    [1] sonly-api   |     at step (/home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:42:23)
    [1] sonly-api   |     at Object.next (/home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:23:53)
    [1] sonly-api   |     at /home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:17:71
    [1] sonly-api   |     at new Promise (<anonymous>)
    [1] sonly-api   |     at __awaiter (/home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:13:12)
    [1] sonly-api   |     at SelectQueryBuilder.executeEntitiesAndRawResults (/home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1344:16)
    [1] sonly-api   |     at SelectQueryBuilder.<anonymous> (/home/node/src/query-builder/SelectQueryBuilder.ts:1153:47)
    [1] sonly-api   |     at step (/home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:42:23)
    [1] sonly-api   |     at Object.next (/home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:23:53)
    [1] sonly-api   |     at /home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:17:71
    [1] sonly-api   |     at new Promise (<anonymous>)
    [1] sonly-api   |     at __awaiter (/home/node/app/node_modules/typeorm/query-builder/SelectQueryBuilder.js:13:12)
    

    The generated query :

    SELECT "company"."id" AS "company_id", "company"."name" AS "company_name", "company"."slug" AS "company_slug", "company"."description" AS "company_description", "company"."validated" AS "company_validated", "company"."moneyRaised" AS "company_moneyRaised", "company"."workforce" AS "company_workforce", "company"."coordinates" AS "company_coordinates", "company"."street" AS "company_street", "company"."city" AS "company_city", "company"."zipcode" AS "company_zipcode", "company"."country" AS "company_country", "company"."creationYear" AS "company_creationYear", "company"."phone" AS "company_phone", "company"."website" AS "company_website", "company"."twitter" AS "company_twitter", "company"."facebook" AS "company_facebook", "company"."videoUrl" AS "company_videoUrl", "company"."superApplicationsResponseRate" AS "company_superApplicationsResponseRate", "company"."newApplicationMail" AS "company_newApplicationMail", "company"."newsletterGeneral" AS "company_newsletterGeneral", "company"."oldId" AS "company_oldId", "company"."oldSlug" AS "company_oldSlug", "company"."coverId" AS "company_coverId", "company"."accountId" AS "company_accountId", "company"."incubatorId" AS "company_incubatorId", "account"."id" AS "account_id", "account"."type" AS "account_type", "account"."email" AS "account_email", "account"."admin" AS "account_admin", "account"."cguValidated" AS "account_cguValidated", "account"."linkedinId" AS "account_linkedinId", "account"."sponsorCode" AS "account_sponsorCode", "account"."stripeUserId" AS "account_stripeUserId", "account"."billedMonthsCountForCurrentSubPeriod" AS "account_billedMonthsCountForCurrentSubPeriod", "account"."totalMonthsCountForAllSub" AS "account_totalMonthsCountForAllSub", "account"."renewSub" AS "account_renewSub", "account"."currentSubscription" AS "account_currentSubscription", "account"."currentSubscriptionStartDate" AS "account_currentSubscriptionStartDate", "account"."isDelinquant" AS "account_isDelinquant", "account"."hasSubscribedOnce" AS "account_hasSubscribedOnce", "account"."nextSubscriptionType" AS "account_nextSubscriptionType", "account"."language" AS "account_language", "account"."wantsToBeDeleted" AS "account_wantsToBeDeleted", "account"."createDate" AS "account_createDate", "account"."updateDate" AS "account_updateDate", "account"."deleteDate" AS "account_deleteDate", "account"."lostPasswordToken" AS "account_lostPasswordToken", "account"."passwordLostMailSendedDate" AS "account_passwordLostMailSendedDate", "account"."oldId" AS "account_oldId", "account"."oldSlug" AS "account_oldSlug", "account"."profilePictureId" AS "account_profilePictureId", "account"."godFatherId" AS "account_godFatherId", "profilePicture"."id" AS "profilePicture_id", "profilePicture"."awsKey" AS "profilePicture_awsKey", "profilePicture"."publicUrl" AS "profilePicture_publicUrl", "incubator"."id" AS "incubator_id", "incubator"."name" AS "incubator_name", "incubator"."coordinates" AS "incubator_coordinates", "incubator"."street" AS "incubator_street", "incubator"."city" AS "incubator_city", "incubator"."zipcode" AS "incubator_zipcode", "incubator"."country" AS "incubator_country", "incubator"."validated" AS "incubator_validated", "incubator"."createDate" AS "incubator_createDate", "incubator"."updateDate" AS "incubator_updateDate", "incubator"."deleteDate" AS "incubator_deleteDate", "features"."id" AS "features_id", "features"."label" AS "features_label", "features"."iconCode" AS "features_iconCode", "features"."companyId" AS "features_companyId", "founders"."id" AS "founders_id", "founders"."firstname" AS "founders_firstname", "founders"."lastname" AS "founders_lastname", "founders"."quote" AS "founders_quote", "founders"."avatarId" AS "founders_avatarId", "founders"."companyId" AS "founders_companyId", "founderAvatar"."id" AS "founderAvatar_id", "founderAvatar"."awsKey" AS "founderAvatar_awsKey", "founderAvatar"."publicUrl" AS "founderAvatar_publicUrl", "activities"."id" AS "activities_id", "activities"."iconName" AS "activities_iconName", "activities"."nameId" AS "activities_nameId", "pictures"."id" AS "pictures_id", "pictures"."companyId" AS "pictures_companyId", "pictures"."photoId" AS "pictures_photoId", "photo"."id" AS "photo_id", "photo"."awsKey" AS "photo_awsKey", "photo"."publicUrl" AS "photo_publicUrl" FROM "company" "company" LEFT JOIN "account" "account" ON "account"."id"="company"."accountId"  LEFT JOIN "media" "profilePicture" ON "profilePicture"."id"="account"."profilePictureId"  LEFT JOIN "incubator" "incubator" ON "incubator"."id"="company"."incubatorId"  LEFT JOIN "feature" "features" ON "features"."companyId"="company"."id"  LEFT JOIN "founder" "founders" ON "founders"."companyId"="company"."id"  LEFT JOIN "media" "founderAvatar" ON "founderAvatar"."id"="founders"."avatarId"  LEFT JOIN "company_activities_activity" "company_activities" ON "company_activities"."companyId"="company"."id" LEFT JOIN "activity" "activities" ON "activities"."id"="company_activities"."activityId"  LEFT JOIN "company_pictures" "pictures" ON "pictures"."companyId"="company"."id"  LEFT JOIN "media" "photo" ON "photo"."id"="pictures"."photoId" WHERE account."isDelinquant" IS FALSE AND "company"."validated" IS FALSE ORDER BY company."creationYear" DESC

    Removing the orderBy clause resolves the problem, as others said before me.

  8. RDeluxe commented on Jul 26, 2018

    @RDeluxe

    Ok, to answer my own problem:
    qb = qb.addOrderBy(${qb.alias}."${k}", opt);

    has to be changed into

    qb = qb.addOrderBy(${qb.alias}.${k}, opt);

  9. ShepelievD commented on Sep 15, 2018

    @ShepelievD

    @popovicidinu @d-bechtel @mentos1386 guys, looks like you have different columns names (I had the issue), for example:
    in a model you have createdAt, but in a database it is created_at

  10. jnnkky commented on Nov 19, 2018

    @jnnkky
    Contributor

    i have the same error with this query:
    let query = this.activityRepository.createQueryBuilder('activity')
    .select()
    .addSelect('user.email as email')
    .innerJoinAndSelect('activity.user', 'user')
    .skip(0)
    .take(10)
    .orderBy('activity.end_date', 'DESC')
    .where('user.email = :email').setParameter('email', userProfile.email);
    let activities = await query.getMany();

    if i use .limit(10) instead of .take(10), it works, but query returns duplicates.
    if i remove the orderBy clause it works, too. So i think the bug exists in combination of take and orderBy.

    I can confirm there is an issue here with the combination of take and orderBy. The query executes fine on the db directly but with TypeORM it fails.

    @popovicidinu @d-bechtel @mentos1386 guys, looks like you have different columns names (I had the issue), for example:
    in a model you have createdAt, but in a database it is created_at

    Also this is not the case for me as I am already escaping my column name, which also is not all lowercase in my failing example.

  11. benfavre commented on Jan 11, 2019

    @benfavre

    Can you have a look a this please ?
    I get

    [watch:server:helper] TypeError: Cannot read property 'databaseName' of undefined
    [watch:server:helper]     at /src/query-builder/SelectQueryBuilder.ts:1857:114
    [watch:server:helper]     at Array.map (<anonymous>)
    [watch:server:helper]     at SelectQueryBuilder.createOrderByCombinedWithSelectExpression (src/query-builder/SelectQueryBuilder.ts:1852:14)
    [watch:server:helper]     at SelectQueryBuilder.<anonymous> (/src/query-builder/SelectQueryBuilder.ts:1770:46)
    [watch:server:helper]     at step (i/node_modules/typeorm/query-builder/SelectQueryBuilder.js:42:23)
    [watch:server:helper]     at Object.next (/node_modules/typeorm/query-builder/SelectQueryBuilder.js:23:53)
    [watch:server:helper]     at /node_modules/typeorm/query-builder/SelectQueryBuilder.js:17:71
    [watch:server:helper]     at new Promise (<anonymous>)
    [watch:server:helper]     at __awaiter (/node_modules/typeorm/query-builder/SelectQueryBuilder.js:13:12)
    [watch:server:helper]     at SelectQueryBuilder.executeEntitiesAndRawResults (/api/node_modules/typeorm/query-builder/SelectQueryBuilder.js:1368:16)
    
    

    If I specify any type of orderBy

  12. pleerock commented on Jan 13, 2019

    @pleerock
    Member

    as @ShepelievD pointed this error usually happen when invalid names are specified. Everybody encouraged this issue should check names they are using in queries.

  13. benfavre commented on Jan 13, 2019

    @benfavre

    I did see that, and have been trying multiple combinations of names, ...
    The error message simply isn't helpfull and debugging is painfull.
    Maybe something can be done to hint on the wrong name usage ?

  14. benfavre commented on Mar 4, 2019

    @benfavre

    For future me, comming back to this post again, please check the spelling on the orderby column name.

  15. 1 remaining item

  16. jtushman commented on Mar 22, 2019

    @jtushman

    @jannikkeye did you find a work around? I also have my names escaped, and have this issue with take combined with orderBy

  17. victordidenko commented on Mar 25, 2019

    @victordidenko

    @pleerock How about null-checking for column, instead of doing column!.databaseName? And if column is null/undefined — throw valid database exception, instead of generic TypeError?

    TypeError
        at .../src/query-builder/SelectQueryBuilder.ts:1866:114
    
  18. m-shev commented on May 12, 2019

    @m-shev

    I solved this problem by removing double quotes around sort key

    works:

    qb.orderBy(${Table.SelectionResource}.createTime, SortOrder.DESC);

    error:
    qb.orderBy(${Table.SelectionResource}."createTime", SortOrder.DESC);

  19. v1d3rm3 commented on Jun 5, 2019

    @v1d3rm3
    Contributor

    I get this error when i'm using leftJoinMapSelect with orderBy in a embedded field.

  20. ahmedosama94 commented on Aug 8, 2019

    @ahmedosama94
    Contributor

    After tinkering around for a while I found that orderBy works by providing the ${alias}.${propertyName}, not the expected ${alias}.${columnName}. I set up my models so that their properties are camelCase and the database tables' columns are in snake_case. I found out the hard way that the orderBy function expects the propertyName instead of the columnName.

    My specific example was as follows:

    • query.orderBy('conversations.created_at') throws an error.
    • query.orderBy('conversations.createdAt') does not.

    Note:
    This indeed only happens when using take alongside orderBy and I can confirm that this does not happen when using limit instead of take, however, limit should not be used when performing joins as indicated in the function's documentation.

  21. michael-golden commented on Dec 10, 2019

    @michael-golden
    Contributor

    I get this error when using leftJoinMapSelect and orderBy, combined with skip() and take()

    This works:

    this.createQueryBuilder('foo')
                .leftJoinAndSelect('foo.bar', 'b')
                .where(`foo.barId = :barId`, { barId: options.barId })
                .orderBy(`foo_baz`, 'ASC')
                .skip((options.index || 0) * (options.limit || 0))
                .take(options.limit);
    

    This does NOT work:

    this.createQueryBuilder('foo')
                .leftJoinAndSelect('foo.bar', 'b')
                .where(`foo.barId = :barId`, { barId: options.barId })
                .orderBy(`foo.baz`, 'ASC')
                .skip((options.index || 0) * (options.limit || 0))
                .take(options.limit);
    

    The difference being the .orderBy() lines.

    I believe the issue stems from the sort string referencing an alias.

    Version: 0.2.19

  22. antowkabond commented on Oct 27, 2020

    @antowkabond

    I have the same issues.
    As for me, it helps

    @Entity({name: 'categories'})
    export class Category extends BaseEntity {
        @PrimaryGeneratedColumn()
        public id: number;
    
        @Column({name: 'my_name'})
        public name: string;
    }
    

    In QueryBuilder use qb.orderBy('categories.name', filter.orderDirection);
    Instead of column name from database. qb.orderBy('categories.my_name', filter.orderDirection);

  23. hypeofpipe commented on Nov 13, 2020

    @hypeofpipe

    I had the same issue. The problem was that we had one private npm package exposing typeorm and another typeorm package installed. I had to use only one package, that was exposing the typeorm.
    Rare case, but maybe would help someone

  24. vthanghq1 commented on Jun 10, 2021

    @vthanghq1

    I have the same issues.
    As for me, it helps

    @Entity({name: 'categories'})
    export class Category extends BaseEntity {
        @PrimaryGeneratedColumn()
        public id: number;
    
        @Column({name: 'my_name'})
        public name: string;
    }
    

    In QueryBuilder use qb.orderBy('categories.name', filter.orderDirection);
    Instead of column name from database. qb.orderBy('categories.my_name', filter.orderDirection);

    thanks. it works like a charm.

  25. kmordan24 commented on Jan 20, 2022

    @kmordan24

    After tinkering around for a while I found that orderBy works by providing the ${alias}.${propertyName}, not the expected ${alias}.${columnName}. I set up my models so that their properties are camelCase and the database tables' columns are in snake_case. I found out the hard way that the orderBy function expects the propertyName instead of the columnName.

    My specific example was as follows:

    • query.orderBy('conversations.created_at') throws an error.
    • query.orderBy('conversations.createdAt') does not.

    Note: This indeed only happens when using take alongside orderBy and I can confirm that this does not happen when using limit instead of take, however, limit should not be used when performing joins as indicated in the function's documentation.

    Thank you!!! This is it right here!! Hours of tinkering and searching threads, and all I had to do was change my orderBy to either:

    orderBy('table_name:columnName') or

     .orderBy({
            "table_name:columnName": "ASC",
            "table_name:anotherColumnName": "ASC",
          })
    

    I tried both orderBy('table_name.column_name' and orderBy('table_name_column_name') and it failed to add the columns to the DISTINCT clause so it would give a SQL syntax error or the ORDERBY would always fail because the column was not part of the DISTINCT column set.

    It appears this bug has existed for years now... the TypeORM docs could at least have a note added about this specific case and the required naming pattern workaround until a fix is complete (which might be a while judging from other thread responses indicating the complexity and required testing).

  26. Razzwan commented on May 15, 2023

    @Razzwan
    Contributor

    But still problem with error message. Not databaseName is wrong, but columnName

  27. Grizley56 commented on Jan 28, 2024

    @Grizley56

    In cases when you want to add custom orderBy logic to your query, and still be able to use .take() in the query, then you can write
    for example:

    createQueryBuilder("lobby") // <- this is working
          .leftJoinAndSelect("lobby.game", "game", 'lobby.id = game.lobby_id')
          .addSelect(`case 
            when game.status = 'inProgress' then 0 
            when game.status = 'waiting' then 1 
            when game.status = 'completed' then 2 end`,
            "status")
          .take(5)
          .skip(10)
          .orderBy('status')
          .getManyAndCount();
    

    instead of

    createQueryBuilder("lobby") // <- this is not working (throwing exception)
          .leftJoinAndSelect("lobby.game", "game", 'lobby.id = game.lobby_id')
          .take(5)
          .skip(10)
          .orderBy(`case 
            when game.status = 'inProgress' then 0 
            when game.status = 'waiting' then 1 
            when game.status = 'completed' then 2 end`)
          .getManyAndCount();
    
  28. Niklas-Mezynski commented on Jan 30, 2024

    @Niklas-Mezynski

    Can confirm what @Grizley56 said.
    If you have any custom logic in your order by, the aliasing mechanism seems to fail. In my case I had a boolean check to filter some fields to come first.
    As workaround, I have changed this:

    qb.orderBy('ps.someColumn > 42', 'DESC').addOrderBy(...);
    //                        ^ will evaluate to 0 or 1
    

    to this:

    qb.addSelect('ps.someColumn > 42', 'someColumnOrderKey');
    qb.orderBy('someColumnOrderKey', 'DESC').addOrderBy(...);
    
  29. crazyoptimist commented on Sep 3, 2024

    @crazyoptimist

    Thank you @michael-golden for the investigation. This is very stupid thing(or maybe a bug?) that is not documented properly. Not fixed to date as of Sep 2024.

  30. mengtongun commented on Sep 25, 2024

    @mengtongun

    In cases when you want to add custom orderBy logic to your query, and still be able to use .take() in the query, then you can write for example:

    createQueryBuilder("lobby") // <- this is working
          .leftJoinAndSelect("lobby.game", "game", 'lobby.id = game.lobby_id')
          .addSelect(`case 
            when game.status = 'inProgress' then 0 
            when game.status = 'waiting' then 1 
            when game.status = 'completed' then 2 end`,
            "status")
          .take(5)
          .skip(10)
          .orderBy('status')
          .getManyAndCount();
    

    instead of

    createQueryBuilder("lobby") // <- this is not working (throwing exception)
          .leftJoinAndSelect("lobby.game", "game", 'lobby.id = game.lobby_id')
          .take(5)
          .skip(10)
          .orderBy(`case 
            when game.status = 'inProgress' then 0 
            when game.status = 'waiting' then 1 
            when game.status = 'completed' then 2 end`)
          .getManyAndCount();
    

    Thanks it work and solve my current problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions