简体   繁体   中英

How can I bulk upsert entities with typeorm?

I'm trying to figure out how to make upsert SQL working with typeorm entities (not using querybuilder!!)

const items = Items[] //Items are the entity which extends BaseEntity
await this.repository.save(items)

this just works fine, but when I look at the console then it makes this SQL:

UPDATE Database.items SET created_at=(something) WHERE id=(something)
UPDATE Database.items SET created_at=(something) WHERE id=(something)
UPDATE Database.items SET created_at=(something) WHERE id=(something)
...

Although it is tied up by START TRANSACTION and COMMIT, I want to do the same thing but not with transaction.

I want something like this:

UPDATE Database.items SET created_at=(something) WHERE id IN (somethings)

How do I make this with only using typeorm's AbstractRepository?

You can refer the docs links updatequery and wheredocs . This should resolve your issue.

import {getConnection} from "typeorm";
const itemIds = [1,2,3];

await getConnection()
.createQueryBuilder()
.update(Item)
.set({ created_at: "something" })
.where("items.id IN (:...ids)", { ids: itemIds })
.execute();

This is how you can do this via the TypeOrm repositories. I didn't test the code in the IDE but I'm 100% sure this approach works.

const items = Items[] //Items are the entity which extends BaseEntity
const itemIds = items.map(item => item.id);
await this.repository.update({id: In(itemIds)}, {createdAt: "something"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM