Search code examples
postgresqlnestjstypeorm

How to get data sorted with relation using TypeORM?


I want to get user data with relation sorted but with this code it just sort the user but I want to sort data that have relation with user I'm using eager, could any one help me ?

getUerWithId(pramas: string): Observable<userEntity[]> {
        return from(this.userRepository.find({
            where: [
                { id: pramas }
            ],
            order:{
                 id:'DESC'
            }
        }))
    }

Solution

  • With the repository, I don't know if it is possible, but you can try with query builder to get ordered relations. Follow example bellow:

    this.userRepository.createQueryBuilder()
          .innerJoinAndSelect("User.notification", "Notification") 
          .orderBy({'Notification.createdAt': 'DESC'})
          .where("User.id = :id", {
            id: Number(id),
          })
          .getOne();
    

    Remember to put the right relationship for your entity, and right names for your properties.