我一直无法找到使用 Sequelize 在 Feathers.js 中连接到多个 MySQL 数据库的记录方式。有没有办法做到这一点?我的用例是能够通过同一操作将数据行插入和获取到多个数据库中,但数据库不一定是相同的架构。
谢谢!
最佳答案
我做了一些本地测试,是可以的。您需要定义 2 个不同的 sequelize 客户端。 如果您使用的是 CLI 生成器并且您设置了一个基于 sequelize 的服务,您应该有一个连接字符串(我的例子是一个 mysql 数据库):
config/default.json 中的数据库连接字符串
"mysql": "mysql://user:password@localhost:3306/your_db"
src根目录下的
sequelize.js
为了创建第二个sequelize客户端
在
config/default.json
中创建一个新的连接字符串"mysql2": "mysql://user:password@localhost:3306/your_db_2"
创建 sequelize.js 的副本并将其命名为
sequelize2.js
const Sequelize = require('sequelize');
module.exports = function (app) { const connectionString = app.get('mysql2'); const sequelize2 = new Sequelize(connectionString, { dialect: 'mysql', logging: false, operatorsAliases: false, define: { freezeTableName: true } }); const oldSetup = app.setup; app.set('sequelizeClient2', sequelize2); app.setup = function (...args) { const result = oldSetup.apply(this, args); // Set up data relationships const models = sequelize2.models; Object.keys(models).forEach(name => { if ('associate' in models[name]) { models[name].associate(models); } }); // Sync to the database sequelize2.sync(); return result; }; };
将新的 sequelize 配置添加到您的 app.js
const sequelize2 = require('./sequelize2');
app.configure(sequelize2);
然后在你的模型中到第二个数据库:
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
//load the second client you defined above
const sequelizeClient = app.get('sequelizeClient2');
//to check if connect to a different db
console.log ( sequelizeClient )
//your model
const tbl = sequelizeClient.define('your_table', {
text: {
type: DataTypes.STRING,
allowNull: false
}
}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});
// eslint-disable-next-line no-unused-vars
tbl.associate = function (models) {
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
};
return tbl;
};
为了工作,您需要 2 个不同的服务,每个服务使用不同的数据库。 如果您想通过单个操作进行放置或获取,您可以在其中一项服务中创建一个前/后 Hook ,并在 Hook 内调用第二个服务。 对于 get 你需要将第二个服务的结果添加到你的钩子(Hook)结果中
关于mysql - 使用 Sequelize 连接到 Feathers.js 中的多个 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54788243/