如何在Sails.js中定义两个MySQL数据库连接 [英] How to define two MySQL database connections in Sails.js

查看:166
本文介绍了如何在Sails.js中定义两个MySQL数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用sails.js v0.10 rc8,我的应用程序与mysql数据库建立了1个连接,对于一个给定的模型,我希望从另一个数据库中获取数据.

Using sails.js v0.10 rc8, my app had 1 connection to a mysql database and I would liked for a given model that the data are fetched from another database.

有可能吗?如果是,该如何实现?

Is it possible ? If yes, how to acheive this ?

谢谢

推荐答案

是的,您可以定义多个连接并将每个模型设置为使用不同的模型.请参阅有关连接的文档进行全面审核.

Yes, you can define multiple connections and set each model to use a different one. Please see the documentation on connections for a full review.

您可以在 config/connections.js 文件中根据需要设置任意数量的连接.您甚至可以使用同一适配器设置多个连接:

You can set up as many connections as you need in your config/connections.js file. You can even set up multiple connections using the same adapter:

module.exports.connections = {
  // A MySQL connection
  mysql1: {
    adapter: 'sails-mysql',
    user: 'root',
    host: 'localhost',
    database: 'database1'
  },
  // Another MySQL connection, same server, different database
  mysql2: {
    adapter: 'sails-mysql',
    user: 'root',
    host: 'localhost',
    database: 'database2'
  },
  // A Postgresql connection
  postgres: {
    adapter: 'sails-postgresql',
    user: 'postgres',
    host: 'localhost',
    database: 'mypsqldb'
  }
};

然后在模型类文件中,指定要用于该模型的连接:

Then in your model class file, specify the connection to use for that model:

module.exports = {
    connection: 'mysql1',
    attributes: {...}
}

要为模型指定默认连接,请在 config/models.js 中进行设置:

To specify the default connection for models, set it in config/models.js:

module.export.models = {
    connection: 'mysql2'
};

这篇关于如何在Sails.js中定义两个MySQL数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆