如何使用 mikro-orm 将选择查询的结果插入到表中

huangapple go评论98阅读模式
英文:

How to insert into a table the result of a select query with mikro-orm

问题

I make a project with PostgreSQL and I use mikro-orm to work with it.

There is a table of the following structure:

id | foreign_id | created_at
---+------------+-----------
 1 |          2 | 2023-05-29

It may contain multiple items with a single foreign_id. And I need to duplicate every row with foreign_id = 31, but with foreign_id = 42 and the current date. I could write something like:

const entities = await entityRepo.findAll({ foreign_id: 31 });

for (const entity of entities) {
    const newEntity = entityRepo.create({ ...entity, foreign_id: 42, created_at: now() })
    entityRepo.persist(newEntity);
}

entityRepo.flush();

But it requires all the entities to be loaded into the memory of a Node.js app. In pure SQL, I could write something like this:

INSERT INTO my_table (id, foreign_id, created_at)
SELECT                id,         42, now()
FROM my_table
WHERE foreign_id = 31;

How to perform the same query with mikro-orm?

英文:

I make a project with postgresql and I use mikro-orm to work with it.

There is a table of the following structure:

id | foreign_id | created_at
---+------------+-----------
 1 |          2 | 2023-05-29

It may contain multiple items with a single foreign_id. And I need to duplicate every row with foreign_id = 31, but with foreign_id = 42 and current date. I could write something like:

const entities = await entityRepo.findAll({ foreign_id: 31 });

for (const entity of entities) {
    const newEntity = entityRepo.create({ ...entity, foreign_id: 42, created_at: now() })
    entityRepo.persist(newEntity);
}

entityRepo.flush();

But it requires all the entities to be loaded into the memory of a nodejs app. In pure SQL, I could write something like this:

INSERT INTO my_table (id, foreign_id, created_at)
SELECT                id,         42, now()
FROM my_table
WHERE foreign_id = 31;

How to perform the same query with mikro-orm?

答案1

得分: 1

如果您希望执行相同的查询,请使用相同的查询,对于ORM难以完成的部分,使用原始SQL没有问题。您可以使用em.execute()来执行原始SQL,或者使用knex构建查询,可以使用em.getKnex()来获取knex对象。

英文:

If you want the same query, then use the same query, there is no shame in using raw SQL for the parts that are not easily done with the ORM. You have the em.execute() for that. Or build it with knex, you have em.getKnex() for that.

huangapple
  • 本文由 发表于 2023年5月30日 03:17:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定