I have the following typeorm code in a for loop:
const user = await User.create({
name: 'bobby',
}).save()
await Post.create({
title: 'test'
userId: user.id,
}).save();
I tried the following code but I get an error about user.id being null:
const user = User.create({
name: 'bobby',
})
const post = Post.create({
title: 'test'
userId: user.id,
}).save();
await Post.insert(post);
await User.insert(user);
Is there a way to solve this without outright creating a entity new table?
You have to successfully create User
before getting its id
.
// create new user
const user1 = new User();
user1.name = 'bobby';
// save new user
const userRepo = AppDataSource.getRepository(User);
await userRepo.save(user1);
// create new post
const post1 = new Post();
post1.title = 'test';
post1.userId = user1.id;
// maybe better if you use relation: post1.user = user1;
// save new post
const postRepo = AppDataSource.getRepository(Post);
await postRepo.save(post1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.