【TypeORM】INSERTで覚えておきたい4つのやり方(と外部キーの指定方法)
環境
はじめに(外部キーの指定方法)
author has_many books
という関連があった時に、新たに book レコードを作りたいと仮定します。
普通にエンティティを書いただけでは、外部キー(Bookエンティティの authorId
)は、データベースには生成されますが、エンティティファイルには現れません。
後述する何れの場合も、このカラムに直接アクセスしたい場合は、エンティティに追加する必要があります。
// (1) このカラムを追加します
@Column()
authorId!: number
@Index()
@ManyToOne(() => Book, (author) => author.books)
// (2) この @JoinColumn を追加します
@JoinColumn({ name: 'authorId' })
author!: Author
ドキュメント: https://typeorm.io/#/relations-faq/how-to-use-relation-id-without-joining-relation
尚、これでは定義が重複してしまうので、「authorId
だけ定義して、 リレーション(この場合は author
)を定義しなくて良い方法はありますか?」という質問がありますが、どうやらなさそうです。
https://github.com/typeorm/typeorm/issues/4569
saveに直接objectを渡す
await this.bookRepo.save({
title,
pages: 300,
authorId: 1,
})
new を使う
const book = new Book()
book.title = title
book.pages = 300
book.authorId = 1
await this.bookRepo.save(book)
create を使う
const book = this.bookRepo.create({
title,
pages: 300,
authorId: 1,
})
await this.bookRepo.save(book)
createQueryBuilder を使う
this.booktRepo.createQueryBuilder()
.insert()
.into(Book)
.values([
{ title },
{ pages: 300 },
{ authorId: 1 },
])
.execute()
await this.bookRepo.save({
title,
pages: 300,
authorId: 1,
})
const book = new Book()
book.title = title
book.pages = 300
book.authorId = 1
await this.bookRepo.save(book)
create を使う
const book = this.bookRepo.create({
title,
pages: 300,
authorId: 1,
})
await this.bookRepo.save(book)
createQueryBuilder を使う
this.booktRepo.createQueryBuilder()
.insert()
.into(Book)
.values([
{ title },
{ pages: 300 },
{ authorId: 1 },
])
.execute()
const book = this.bookRepo.create({
title,
pages: 300,
authorId: 1,
})
await this.bookRepo.save(book)
this.booktRepo.createQueryBuilder()
.insert()
.into(Book)
.values([
{ title },
{ pages: 300 },
{ authorId: 1 },
])
.execute()
ドキュメント: https://orkhan.gitbook.io/typeorm/docs/insert-query-builder
Author And Source
この問題について(【TypeORM】INSERTで覚えておきたい4つのやり方(と外部キーの指定方法)), 我々は、より多くの情報をここで見つけました https://qiita.com/piggydev/items/58603bd9f8309c7eb022著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .