I've been working on building a server using typeORM and NestJS. I have set up a one-to-one relationship between my User and Shop classes, with the foreign key shopId in the User table. However, when trying to retrieve a user, the associated shop is not being fetched. What should I do? Here's my User class:
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column('text')
name: string;
@Column('text')
email: string;
@Column('text')
phoneNumber: string;
@Column('text')
password: string;
@Column('boolean')
isAdmin: boolean;
@OneToOne(() => Shop, (shop) => shop.user)
@JoinColumn()
shop: Shop;
constructor(
name: string,
email: string,
phoneNumber: string,
password: string,
) {
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
this.password = password;
}
}
And here's my Shop class:
export class Shop {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToOne(() => User, (user) => user.shop) // specify inverse side as a second parameter
user: User;
@OneToMany(() => Order, (order) => order.shop)
orders: Order[];
@OneToMany(() => Product, (product) => product.shop)
products: Product[];
constructor(name: string) {
this.name = name;
}
The function in UserService that fetches the desired User is as follows:
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
private dataSource: DataSource,
) {}
findOneByPhoneNumber(phoneNumber: string): Promise<User> {
return this.userRepository.findOneBy({ phoneNumber });
}
...
}
However, when the function returns a user, the associated shop is missing from the response, with only the other user fields being returned.
This is the current response:
{
name: 'test',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d19081e192d0a000c0401430e0200">[email protected]</a>',
phoneNumber:'+251912345678',
password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
id: 1,
isAdmin: false
}
I was expecting the related shop object to be included in the response. What am I missing or doing wrong here?