Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with the parameters in my TypeORM WHERE clause for the QueryBuilder?

Can someone explain to me what I am doing wrong when using the parameters for my where clause?

This next block gives me the error below it:

@EntityRepository(Something)
export class SomethingRepository extends Repository<Something>{

  findByUserAndSomethingById(userId: number, spotId: number){
    const thing = this.createQueryBuilder('something')
    .where('something.userId = :id', {id: userId})
    .andWhere('something.id = :id',{id: spotId}).getOne();
    return thing;
  }
}
QueryFailedError: column something.userid does not exist

This request gives me the right result.

@EntityRepository(Something)
export class SomethingRepository extends Repository<Something>{

  findByUserAndSomethingById(userId: number, spotId: number){
    const thing = this.createQueryBuilder('something')
    .where(`"something"."userId" = ${userId}`)
    .andWhere('something.id = :id',{id: spotId}).getOne();
    return thing;
  }
}

Update: Example repo for reproduction and typeorm issue on github.

like image 305
fabianmoronzirfas Avatar asked Dec 01 '25 04:12

fabianmoronzirfas


2 Answers

The issue with the original query is that the parameter name id was used more than once:

    .where('something.userId = :id', {id: userId})
    .andWhere('something.id = :id',{id: spotId}).getOne();

These need to be unique according to this note in the docs.

like image 180
Daniel Carmingham Avatar answered Dec 06 '25 06:12

Daniel Carmingham


The solution is to load the relations of my entity. As I understand it.

findByUserAndSomethingById(userId: number, spotId: number) {
    const thing = this.createQueryBuilder('something')
    .innerJoin('something.user', 'user')
      .where('user.id = :uid', { uid: userId })
      .andWhere('something.id = :sid', { sid: spotId }).getOne();
    return thing;
}

Thanks to @Mukyuu for all your effort to help me.

like image 28
fabianmoronzirfas Avatar answered Dec 06 '25 06:12

fabianmoronzirfas