sirzento
sirzento

Reputation: 717

Select with custom field

I have an entity toy with many properties but also a few OneToMany and ManyToOne relations. To get all entries where column deleted is not true I would write:

findAll() {
  return this.toyRepository.find({
    where: {
      deleted: Not(true)
    }
  });
}

It gets all entries I want but this entity has a ManyToOne relation to user. I want to get all entries but with an extra property user that contains only the username of that user. I can load the whole relation if adding relations: ['user'] but that's not what I want.

So I need to use the querybuilder. I came up with:

return this.toyRepository
  .createQueryBuilder('toy')
  .select('toy.*')
  .addSelect('userEntity.username', 'user')
  .where('toy.deleted != 1')
  .leftJoin('toy.user', 'userEntity')
  .getRawMany();

This will get the entries I want but contains all other ManyToOne relations with a null value (if there is no entry connected to it) like "manufacturerId", "userId", "brandId", etc. I want the entry without the relation connection.

The only way I know is to not use toy.* and use toy.id, toy.name, toy.descritpion, toy.serial, toy.serial2, toy.size, [many more ...] instead, but it doesn't seem right to hardcode all column names.

Is there any other way to do this?

Upvotes: 0

Views: 177

Answers (1)

fujy
fujy

Reputation: 5264

In your find() call, you can make use of relations and select attributes

findAll() {
  return this.toyRepository.find({
    where: {
      deleted: Not(true)
    },
    relations: {
      user: true
    },
    select: {
      user: {
        id: true,
        username: true,
        // ... any other columns that you want to select
      }
    }
  });
}

Upvotes: 0

Related Questions