1
votes

I am playing around with NestJs using TypeORM along with MySQL.

I have went via documentation, and I have made basic CRUD app running locally. I have built in searches (via Repository) by id, but I would need to implement search by custom column as well.

For example I have this entity:

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  username: string;

  @Column()
  first_name: string;

  @Column()
  last_Name: string;

  @Column()
  gender: string;
  

And in my repository, I have these built in methods:

async findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: string): Promise<User> {
    return this.usersRepository.findOne(id);
  }
  

And it works just fine, as expected. I would need another custom search, so I can search also by username, how can I achieve that? I would need something like this:

findByUsername(username: string): Promise<User> {
    return this.usersRepository.findByUsername(username);
  }

I assume I have to implement custom query, but I have no clue where to do it :(

4

4 Answers

6
votes

Here is the simpler solution:

findByUsername(username: string): Promise<User | undefined> {
    return this.usersRepository.findOne({ username }); 
}
2
votes

You can use this code

findByName(user_name: string): Promise<User> {
    return this.usersRepository.findOne({ user_name }); 
}
0
votes

I managed to achieve it, by using queryBuilder

So this is how my function looks now:

findByUsername(username: string): Promise<User | undefined> {
    const user = getRepository(User)
      .createQueryBuilder("user")
      .where("user.username = :username", { username: username })
      .getOne();

    return user;
  }
-1
votes
const firstUser = await connection
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne();