简体   繁体   English

如何使用Kraken.js为书架配置Knex

[英]How to configure Knex for Bookshelf with Kraken.js

I am trying to integrate Knex (which I used on a previous app that did not use kraken.js), but I need it now for my ORM (bookshelf.js). 我正在尝试集成Knex(我在以前未使用kraken.js的应用程序中使用了Knex),但现在我的ORM(bookshelf.js)需要它。 I came across this post while researching, but I'm still a little fuzzy. 我在研究时碰到了这篇文章 ,但是我还是有点模糊。 This is for a mysql DB. 这是针对mysql DB的。

Where should I create the connection so I can pass it to the bookshelf object for my models? 我应该在哪里创建连接,以便可以将其传递给模型的书架对象?

Just set it as a global object in your onconfig() handler. 只需在onconfig()处理程序中将其设置为全局对象即可。 Something like this: 像这样:

config.json : config.json

//...
"databaseConfig": {
  "host": // db host
  "database": // db name
  "user": //db user
  "password": //db pass
},

lib/bs.js LIB / bs.js

var bookshelf = require('bookshelf')(global.db);
module.exports = function Bookshelf() {
  return bookshelf;
};

index.js : index.js

var options = {
  onconfig: function(config, next) {
    global.db = require('knex')({
      client: 'mysql',
      connection: config.get('databaseConfig')
    });

    next(null, config);
  }
};

When you need your bookshelf object to define your models, you can include it and it's ready to go: 当您需要书架对象来定义模型时,可以包括它,并且可以使用了:

models/accounts.js 车型/ accounts.js

   var bs = require('../lib/bs')();

    var Account = bs.Model.extend({
      idAttribute: 'id',
      tableName: 'accounts'
    });

    module.exports = function AccountModel() {
      return Account;
    }

There's other ways to do it, but this is clean and should suffice for what you need. 还有其他方法可以执行此操作,但这很干净,可以满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM