繁体   English   中英

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

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

我正在尝试集成Knex(我在以前未使用kraken.js的应用程序中使用了Knex),但现在我的ORM(bookshelf.js)需要它。 我在研究时碰到了这篇文章 ,但是我还是有点模糊。 这是针对mysql DB的。

我应该在哪里创建连接,以便可以将其传递给模型的书架对象?

只需在onconfig()处理程序中将其设置为全局对象即可。 像这样:

config.json

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

LIB / bs.js

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

index.js

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

    next(null, config);
  }
};

当您需要书架对象来定义模型时,可以包括它,并且可以使用了:

车型/ accounts.js

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

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

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

还有其他方法可以执行此操作,但这很干净,可以满足您的需求。

暂无
暂无

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

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