簡體   English   中英

QueryBuilder 的 Typeorm WHERE 子句中的參數有什么問題?

[英]What is wrong with the parameters in my Typeorm WHERE clause for the QueryBuilder?

有人可以向我解釋在使用 where 子句的參數時我做錯了什么嗎?

下一個塊給了我下面的錯誤:

@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

這個請求給了我正確的結果。

@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;
  }
}

更新:例回購繁殖和typeorm問題在GitHub上。

我不能肯定,因為它不在文檔中 但是當我使用TypeORM QueryBuilder 對SQL 運行查詢時,通常需要在別名和字段名前后添加另一個引號。

例如,在您的情況下,您需要使用: .where('"something"."userId"' = :id', {id: userId})作為您在第二個示例中的使用方式: .where('"something"."userId"' = ${userId})

調試的一種方法通常是檢查失敗的已執行查詢。 是否所有查詢都按照您正常執行的方式執行,或者是否缺少引號。

解決方案是加載我的實體的關系。 據我了解。

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;
}

感謝@Mukyuu 為幫助我所做的一切努力。

原始查詢的問題是參數名稱id被多次使用:

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

根據文檔中的此注釋,這些必須是唯一的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM