我正在使用typeORM和NestJS来构建一个服务器我在User类和Shop类以及User表中的外键shopId之间有一对一的关系,但是当我试图获取用户时,与之相关的商店没有被获取,我该怎么办?我的User类如下:
@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;
}
}
我的店铺类如下所示:
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;
}
UserService中获取所需用户的函数为:
export class UserService {
constructor(
@InjectRepository(User)
private userRepository: Repository<User>,
private dataSource: DataSource,
) {}
findOneByPhoneNumber(phoneNumber: string): Promise<User> {
return this.userRepository.findOneBy({ phoneNumber });
}
...
}
当函数返回用户时,与之相关的商店不存在,并且仅发送用户类中的其它字段。
这就是我得到的:
{
name: 'test',
email: 'test@gmail.com',
phoneNumber:'+251912345678',
password: '$2b$10$Q5FR7cleRkJebMPy.cPWIuPLQrNTMB3kxXWXPiRlFH99U4WfFqyd6',
id: 1,
isAdmin: false
}
但是我希望相关的商店对象也在响应中,我在这里遗漏了什么或做错了什么?
1条答案
按热度按时间6jjcrrmo1#
必须将UserService类中的函数更改为
结果如下