learner
learner

Reputation: 1

executing direct query in controller in loopback

I have started working in loopback 4.I have created a default CRUD controller with basic CRUD operations which can get 'the table data', 'the table record for particular id' etc.. what I need now is I want to execute my own query for this table. How to write a query in controller and execute it?

/* below is the default function to get table data*/

@get('/customers', {
    responses: {
      '200': {
        description: 'Array of customers model instances',
        content: {
          'application/json': {
            schema: {type: 'array', items: {'x-ts-type': Customers}},
          },
        },
      },
    },
  })

  async find(
      @param.query.object('filter', getFilterSchemaFor(Customers)) filter?: Filter,
           : Promise<Customers[]> {
      if (limit > 100) limit = 100; // your logic
      return await this.CustomersRepository.find(filter);
  }

the type of code I want is,

Execute(dataset, sqlstatement); //is that available?

Upvotes: 0

Views: 253

Answers (1)

Miroslav Bajtoš
Miroslav Bajtoš

Reputation: 10785

Support for executing raw database queries was added recently by the pull request #2681, this functionality is provided by Repository method execute.

Please note that they query format is connector-specific. For example, if you are using MySQL database, then you can write the following query:

await this.CustomersRepository.execute(
  // the query template, use "?" for variables to AVOID SQL INJECTIONS ATTACKS!
  'SELECT TOP ? * FROM CUSTOMERS',
  // the values to use for variables
  [limit]);

Upvotes: 2

Related Questions