在typeorm官方文档https://typeorm.io/#/many-to-one-one-to-many-relations中有关于如何执行此操作的描述。但是我无法使用df = read.table(text = ' grp date long lat rowid
1 1 1995-07-01 11 12 1
2 1 1995-07-05 3 0 2
3 1 1995-07-09 13 4 3
4 1 1995-07-13 4 25 4
5 2 1995-03-07 12 6 1
6 2 1995-03-10 3 27 2
7 2 1995-03-13 34 8 3
8 2 1995-03-16 25 9 4', h = TRUE)
和Repository
方法在NestJS中执行相同的操作。
我已经写了这些实体(省略了其他列)
insert
我已经尝试过类似的事情
@Entity()
export class News {
@OneToMany(type => NewsImage, image => image.news)
public images: NewsImage[];
}
@Entity()
export class NewsImage {
@ManyToOne(type => News, news => news.images)
public news: News;
}
它插入新闻和图片,但图片的function first() {
const news = new News();
const image = new NewsImage();
news.images = [ image ];
return from(this.newsRepo.insert(news))
.pipe(
switchMap(() => this.imageRepo.insert(image)),
);
}
function second() {
const news = new News();
const image = new NewsImage();
image.news = news;
return from(this.imageRepo.insert(image))
.pipe(
switchMap(() => this.newsRepo.insert(news)),
)
}
是newsId
。
答案 0 :(得分:1)
声明new News()
会创建一个新实体,但不会将其保存到数据库中。您首先需要insert
或.save()
对象news
,然后将其添加到image
。
async function first() {
// you can .save() it however you want, the point is it must be saved to the db
const news = await News.create({ title: 'Async rules the world' }).save()
const image = new NewsImage()
image.news = news // now news has an id from the database
// ...
}
答案 1 :(得分:0)
检查级联属性
@Entity()
export class News {
@OneToMany(type => NewsImage, image => image.news, { cascade: ['insert', 'update'] })
public images: NewsImage[];
}
然后,如果您执行类似的操作
let news = {
images: [{
date: "",
etc: ""
}],
title: ""
}
如果您致电this.repository.save(news)
,它将保存新闻和图像。并且也更新。在typeorm文档上查看有关此内容的更多文档。