環境
はじめに(外部キーの指定方法)
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()
ドキュメント: https://orkhan.gitbook.io/typeorm/docs/insert-query-builder