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('.... ?? )', '...'))
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.
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;
}
}
in strapi V4 use this:
await strapi.db.connection.select("*").from("demos")
With Strapi v4 use:
strapi.db.connection.raw
instead of
strapi.connections.default.raw
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With