Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM upsert - create if not exist

Does TypeORM include some functionnality to avoid this :

let contraption = await thingRepository.findOne({ name : "Contraption" });  if(!contraption) // Create if not exist {     let newThing = new Thing();     newThing.name = "Contraption"     await thingRepository.save(newThing);     contraption = newThing; } 

Something like :

let contraption = await thingRepository.upsert({ name : "Contraption" }); 
like image 546
LucasBordeau Avatar asked Oct 14 '17 14:10

LucasBordeau


2 Answers

As pointed out by Tomer Amir, there is currently a partial solution for real upsert and a feature request is ATM opened on TypeORM's repository :

TypeORM upsert feature request

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 !"}); 
like image 61
LucasBordeau Avatar answered Oct 02 '22 20:10

LucasBordeau


For anyone finding this in 2021, Typeorm's Repository.save() method will update or insert if it finds a match with a primary key. This works in sqlite too.

From the documentation:

 /**  * Saves all given entities in the database.  * If entities do not exist in the database then inserts, otherwise updates.  */ 
like image 34
DonkeyKong Avatar answered Oct 02 '22 20:10

DonkeyKong