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 :(
Here is the simpler solution:
findByUsername(username: string): Promise<User | undefined> {
return this.usersRepository.findOne({ username });
}