Objection.js: Bind knex to objection per query, instead of statically

Created on 13 Jun 2018  路  5Comments  路  Source: Vincit/objection.js

Hi
From the little time I've spent investigating objection I really like it and I'm keen to use it in a project.
However in the project I'm working on we have namespaced databases, which means at query time we need to specify which database we're using, not at startup time. This works fine when just using knex on its own, but the way objection binds knex statically at startup doesn't seem to make it possible to do this.

The best way I can think of how it could work is being able to do the following, similar to how transactions are done:

// Initialize knex.
const knex = Knex({
  client: 'sqlite3',
  useNullAsDefault: true,
  connection: {
    filename: 'example.db'
  }
});
const jennifer = await Person
    .query(knex('person_namespace'))
    .insert({firstName: 'Jennifer', lastName: 'Lawrence'});

so you never do Model.knex(knex); at startup.

Do you know if there is currently a way to support this without any code changes?

Thanks

Most helpful comment

@BrendanBall you should also check out the multi tenancy recipe from the docs. It introduces some nice tools for your use case

All 5 comments

Yes, you can pass a knex instance or knex transaction directly to query().

awesome, I only saw in the docs passing an objection transaction through to query() so wasn't sure if it had the same api.
Thanks

@BrendanBall if it helps, we initially started with Sequelize, which proved to be one of the biggest headaches ever, and after migrating to Objection we never looked back.

@BrendanBall you should also check out the multi tenancy recipe from the docs. It introduces some nice tools for your use case

@koskimas this is awesome! I'll be honest I overlooked the recipe books section. Thanks for pointing me to it.

Was this page helpful?
0 / 5 - 0 ratings