Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strapi + knex to execute complex Queries

Tags:

strapi

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('.... ?? )', '...'))
like image 331
JMCHZA Avatar asked Nov 14 '18 13:11

JMCHZA


4 Answers

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.

like image 157
Jim LAURIE Avatar answered Oct 22 '22 04:10

Jim LAURIE


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;
  }
}
like image 28
Dylan Avatar answered Oct 22 '22 05:10

Dylan


in strapi V4 use this:

await strapi.db.connection.select("*").from("demos")
like image 39
Avinash Utekar Avatar answered Oct 22 '22 06:10

Avinash Utekar


With Strapi v4 use:

strapi.db.connection.raw 

instead of

strapi.connections.default.raw
like image 1
Adam Hegge Avatar answered Oct 22 '22 04:10

Adam Hegge