7

How do I get the knex object to execute custom or complex queries within my strapi service?

My Strapi version has the strapi-hook-knex and strapi-hook-bookshelf installed but when I run qb.raw it is an undefined object.

This is to run queries like this:

qb.select(knex.raw('.... ?? )', '...'))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
JMCHZA
  • 71
  • 1
  • 6

5 Answers5

9

You will find it in strapi.connections.default

default if you don't change your connection name. If you did you will have to replace default by your connection name.

Jim LAURIE
  • 3,859
  • 1
  • 11
  • 14
7

Took me awhile to pin down exact syntax for this. Here it is in case helpful to others. Could not have gotten there without Jim LAURIE's answer.

module.exports = {
  async findCustom(ctx) {
    const rawBuilder = strapi.connections.default.raw(
      "select field1 from mytable where field1 = 'x'"
    );
    const resp = await rawBuilder.then();
    return resp.rows;
  }
}
Dylan
  • 151
  • 3
  • 10
7

in strapi V4 use this:

await strapi.db.connection.select("*").from("demos")
2

With Strapi v4 use:

strapi.db.connection.raw 

instead of

strapi.connections.default.raw
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Adam Hegge
  • 21
  • 1
1
console.log(strapi.db.connection.raw("SELECT COUNT(*) FROM public.mytable").then(r => { console.log(r) }, error => {console.log(error)}))
vimuth
  • 5,064
  • 33
  • 79
  • 116
ali
  • 21
  • 2