marco-zan reymerk
marco-zan reymerk

Reputation: 69

Insert using a select in typeorm

I want to reproduce a query where the values are the result of a select in typeorm. The query i want to reproduce is the one i provide here, but i can't find anything in typeorm documentation. (Isnt important what the query does for the answer, i only need to know how to write that "SELECT" in typeorm)

http://typeorm.delightful.studio/classes/_query_builder_insertquerybuilder_.insertquerybuilder.html#values

INSERT INTO `furgpezzo`(`giacenza`, `giacenzaMin`, `pezzoBarcode`, `furgoneTarga`, `invStandardId`) 
    select '0', '5', '234234234234', f.`furgoneTarga`, '1'
    from `furgpezzo` f
    where f.`invStandardId` = '1'
    group by f.`furgoneTarga`

something like:

(Edit:)

return await this.dmDatabase.getRepository(FurgPezzo)
    .createQueryBuilder()
    .insert()
    .into(FurgPezzo)
    .values(   //here put my select   )

Upvotes: 7

Views: 15159

Answers (2)

Ertan Kara
Ertan Kara

Reputation: 326

This is the neatest solution I could come up with, hope it helps future explorers. The answer comments inspired me.

const [selectQuery, params] = this.entityManager
  .createQueryBuilder()
  .select("user.name")
  .from(User, "user")
  .where("user.id IN (:...ids)", {
    ids: [
      "87654321-1234-1234-1234-123456789abc",
      "a9876521-aabb-ccdd-ffaa-123abcdefccc",
    ],
  })
  .getQueryAndParameters();

await this.entityManager.query(
  `
INSERT INTO dummy("name")
${selectQuery}
`,
  params
);

Upvotes: 10

Shinjo
Shinjo

Reputation: 695

Yes you can. From docs:

You can easily create subqueries. Subqueries are supported in FROM, WHERE and JOIN expressions.

Refer to the following posts for example: TypeORM subqueries, Typeorm subquery add select.

You can use subqueries:

return await this.dmDatabase.getRepository(InvStandard)
    .insert()
    .values(qb => {qb.select(FurgPezzo).where()})//here put my select 

// with subquery->

return await this.dmDatabase.getRepository(InvStandard)
    .insert()
    .values(qb => {qb.select(FurgPezzo).where(
            const subQuery = qb.subQuery()
                // your subquery builder
            return "your condition " + subQuery;)})

Upvotes: -4

Related Questions