我在创建两个具有oneToMany和ManyToOne关系的实体时遇到问题。 这些是我的实体:
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToOne(type => User, user => user.photos)
user: User;
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(type => Photo, photo => photo.user)
photos: Photo[];
}
我试图创建一个用户以及3张具有关联关系的照片:
(async () => {
const conn = await createConnection(typeOrmConfig);
console.log('PG connected.');
const photoRepo =await conn.getRepository(Photo)
const userRepo = await conn.getRepository(User);
let user1 = new User();
user1.name = 'Matt';
user1 = await userRepo.save(user1);
let photo1 = new Photo();
photo1.name = "wallpaper"
photo1.user = user1
let photo2 = new Photo();
photo2.name = "zanzibar"
photo2.user = user1
let photo3 = new Photo();
photo3.name = "beach"
photo3.user = user1
await photoRepo.save(photo1)
await photoRepo.save(photo2)
await photoRepo.save(photo3)
// Close connection
await conn.close();
})();
但是每当我尝试打印用户和照片时,我都看不到它们之间的任何关系字段(在每张照片中看不到用户/用户中的照片):
const conn = await createConnection(typeOrmConfig);
console.log('PG connected.');
const photoRepo =await conn.getRepository(Photo)
const userRepo = await conn.getRepository(User);
console.log(await photoRepo.find())
console.log(await userRepo.find())
await conn.close();
输出:
[
Photo { id: 1, name: 'wallpaper' },
Photo { id: 2, name: 'Zanzibar' },
Photo { id: 3, name: 'beach' }
]
[
User { id: 1, name: 'Matt' }
]
我尝试访问user.photos,但未定义 尝试访问photo.user时也是如此。 知道如何解决这个问题吗?