strapi + knex to execute complex Queries
Asked Answered
A

6

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('.... ?? )', '...'))
Acetylide answered 14/11, 2018 at 13:24 Comment(0)
Y
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.

Yeorgi answered 10/12, 2018 at 14:21 Comment(1)
It doesn't work with strapi v4.0.7, on my v3.6.5 it was working fineFausta
C
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;
  }
}
Clareclarence answered 1/6, 2020 at 22:10 Comment(0)
R
7

in strapi V4 use this:

await strapi.db.connection.select("*").from("demos")
Renfred answered 14/3, 2022 at 19:17 Comment(0)
M
2

With Strapi v4 use:

strapi.db.connection.raw 

instead of

strapi.connections.default.raw
Montagnard answered 12/2, 2022 at 18:24 Comment(0)
F
2
console.log(strapi.db.connection.raw("SELECT COUNT(*) FROM public.mytable").then(r => { console.log(r) }, error => {console.log(error)}))
Forjudge answered 11/8, 2022 at 21:21 Comment(0)
M
2
async findCustom(ctx) {
  const rawBuilder = (await strapi.db.connection.select().count().from("users_links").where({group_id:5}));

  try {
    ctx.body = rawBuilder;
  } catch (err) {
    ctx.body = err;
  }
}
Medicaid answered 6/12, 2023 at 1:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.