英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论