TypeORM-带数组参数的查询数据库-Postgres?

时间:2019-12-04 04:49:05

标签: graphql typeorm

我可以用单个整数查询技术字段。我将其设置为数组,并且可以使用它进行完整的CRUD。

具有数组的查询失败。我尝试了更多的WHERE语句,但没有任何效果。从文档,这应该工作。该怎么办?

const techArray = [1, 6];
// const testArray = '{1, 6}';  // error: value.map is not a function
// A Postgres array must be in {}. But this fails with the above error.

return await getRepository(Projects)
   .createQueryBuilder("projects") // Create SQL alias.
   .where("projects.technologies = ANY ( :...id )", { id: techArray })
   // .where(':id = ANY (projects.technologies)', { id: techArray})
   .getMany();

我在GraphQL播放列表中收到的消息:

"syntax error at or near ,"

相关实体:

@Entity()
export class Projects {
  @PrimaryGeneratedColumn()
  project_id: number;
  ...
  @Column('int', { array: true, nullable: true })
  technologies: number;
  ...

1 个答案:

答案 0 :(得分:0)

我认为此解决方案是骇客。由于TypeORM仅适用于一个整数元素的数组,因此我在其中进行了for循环和for循环。我得到了想要的结果,但似乎代码太多了。

public async findById(techArray) {

    let i;
    let items = [];

    for ( i = 0; i < techArray.length; i++ ) {

      let item = [];  // 0 out the array each iteration.

      item.push(techArray[i]);

      let objectArray = await this.entityManager
      .createQueryBuilder(Projects, "projects")
      // This works with [1]
      .where(":...ids = ANY (projects.technologies)", {ids: item})  
      .getMany();

      for ( let j = 0; j < objectArray.length; j++ ) {

        let objects = objectArray[j];
        console.log('objects in service: ', objects);

        items.push(objects);
      }

    }
    console.log('items in service: ', items);
    // This result is used by an Angular component for more processing.
    return await items; 
  }