Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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   )
like image 207
marco-zan reymerk Avatar asked Aug 05 '19 17:08

marco-zan reymerk


People also ask

How do I get Started with typeorm?

The quickest way to get started with TypeORM is to use its CLI commands to generate a starter project. Quick start works only if you are using TypeORM in a NodeJS application.

How do you work with a database in typeorm?

Working with a database starts from creating tables. How do you tell TypeORM to create a database table? The answer is-through the models. Your models in your app are your database tables.

How do I create a new project in typeorm?

Then go to the directory where you want to create a new project and run the command: typeorm init --name MyProject --database mysql Where name is the name of your project and database is the database you'll use.

What is the use of QueryBuilder in typeorm?

QueryBuilder is one of the most powerful features of TypeORM - it allows you to build SQL queries using elegant and convenient syntax, execute them and get automatically transformed entities. When using the QueryBuilder, you need to provide unique parameters in your WHERE expressions. This will not work:


1 Answers

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
      )
like image 147
Ertan Kara Avatar answered Oct 23 '22 05:10

Ertan Kara