1

Following is the record in table -

enter image description here

I need to select records based on the batches (last column). I have my end point like -

http://localhost:3000/batch/Batch 3

This is my controller and works fine and redirect the call to service -

@Get('/batch/:batchName')
  getByBatch(@Param('batchName') batch): Promise<Assignment[]> {
    return this.assignmentService.getByBatch(batch);
  }

This is my service -

async getByBatch(batch: string): Promise<Batch[]> {
    return await getRepository(Assignment)
      .createQueryBuilder('a')
      .where('a.batches CONTAINS :batch', { batch: batch })
      .getMany();
  }

I am not sure as how the query would be formed in this case. I am using typeorm and postgres. For simple queries, I have directly used repository like -

return this.assgRepository.findOne({ id: id });

Following is the entity -

@PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column()
  description: string;

  @Column({ array: true })
  batches: string;

  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  createdAt: string;

I need to pass a batch and fetch records which ever contain that batch.

P.S. If you could also point me as how can I update the batches would be great.

2 Answers 2

1
@Column({type: "simple-array"})
batches: string;

batches should be saved in the form ["batch 1", "batch 2"] and not like [{"batch 1", "batch 2"}]

finally query

where("a.batches IN (:...batch)", { batch: ["batch 1"] })
Sign up to request clarification or add additional context in comments.

Comments

0

This is how I'm doing it and it's

I have my entity like so:

  @Column({ type: 'text', array: true, nullable: true })
  relations?: string[];

I can save using the repository:

await repository.save([{
  relations: ['contact', 'user'],
}]);

And query using the query builder, returning all records that have 'contact' in the "relations" array:

  await repository
    .createQueryBuilder()
    .where('relations && ARRAY[:...relationTable]', {
      relationTable: ['contact'],
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.