我无法找到使用semelize在feathers.js中连接到多个mysql数据库的记录方法。有没有办法做到这一点?我的用例是能够从相同的操作中插入并将一行数据插入多个DB,但DBS不一定是同一模式。
谢谢!
我进行了一些本地测试,这是可能的。您需要定义2个不同的续集客户端。如果您使用的是CLI Generator,并且基于续集设置服务,则应具有连接字符串(我的示例是mysql db):
-
config/default.json
中的DB连接字符串"mysql" : "mysql://user:password@localhost:3306/your_db"
-
src root文件夹中的
sequelize.js
为了创建第二个续集客户端
-
在
中创建一个新连接字符串config/default.json
"mysql2" : "mysql://user:password@localhost:3306/your_db_2"
-
创建sequelize.js的副本,并将其命名
sequelize2.js
const quard quere = 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; }; };
将新的续集配置添加到您的app.js
const sequelize2 = require('./sequelize2');
app.configure(sequelize2);
然后在您的第二个dB的模型中:
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种不同的服务,每种服务都与不同的DB一起工作。如果您想采用单个操作或获得或获得一个操作,则可以在其中一项服务中创建一个前/之后的挂钩,并在挂钩中致电第二个服务。为了获得,您需要将第二个服务的结果添加到钩结果