TypeORM - returns double result

Viewed 431

I have a problem with search by querybuilder in typeorm:

const projects = await this.conn.getRepository(UserProjectRelations).createQueryBuilder('userProject')
            .innerJoin("userProject.userId", "user", "user.id = :userId", { userId: user.id })
            .innerJoinAndSelect("userProject.projectdId", "projectdId")
            .addSelect(['userProject.id', 
                            'userProject.status', 
                           ])
            .getRawMany();

why when i launch this query, in result i get an double rows like id and userProject_id?

output below:

{
    "userProject_id": 1,
    "userProject_status": "Owner",
    "status": "Owner",
    "id": 1
}

i want to return only this two objects:

{
    "status": "Owner",
    "id": 1
}

thanks for any help!

1 Answers

I think that when you use getRawMany() it returns the raw data that you mentioned: userProject_id and userProject_status

What if you tried using getMay() instead. I think that if you do you will get the object in the shape that you desire. Which will be {id, status} only

const projects = await this.conn
  .getRepository(UserProjectRelations)
  .createQueryBuilder('userProject')
  .innerJoin('userProject.userId', 'user', 'user.id = :userId', {
    userId: user.id,
  })
  .innerJoinAndSelect('userProject.projectdId', 'projectdId')
  .addSelect(['userProject.id', 'userProject.status'])
  .getMany(); // Try this instead of getRawMany()

Get Raw will return raw data and give you more than you wanted. Its good for generating fields that don't exist on the entity, for example using sum or avg on some other field value.

Here is some further reading on getting Raw data: https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#getting-raw-results

Related