这里面主要参考的
https://stackoverflow.com/questions/46745688/typeorm-upsert-create-if-not-exist
感觉介绍的方法都不错。
Partial solution :
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(post2)
.onConflict(`("id") DO NOTHING`)
.execute();
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(post2)
.onConflict(`("id") DO UPDATE SET "title" = :title`)
.setParameter("title", post2.title)
.execute();
Old answer actually points to the "update" way of doing what OP was asking for :
There's already a method for it : Repository<T>.save()
, of which documentation says :
Saves all given entities in the database. If entities do not exist in the database then inserts, otherwise updates.
But if you do not specify the id or unique set of fields, the save method can't know you're refering to an existing database object.
So upserting with typeORM is :
let contraption = await thingRepository.save({id: 1, name : "New Contraption Name !"});