0

我正在使用sails js v 1.x构建一个rest api我需要连接两个mysql数据库,所以我在config/datastores.js文件中定义了它们:

module.exports.datastores = {
 default: {
      adapter: require('sails-mysql'),
      url: 'mysql://root:12345@192.168.0.5:3306/test',
    },
    mysqldb: {
      adapter: require('sails-mysql'),
      url: 'mysql://root:12345@192.168.0.5:3306/test2',
    },

};

在我的控制器中,我有这个功能需要通过加入数据库测试以及 test2 来获取数据

module.exports = {

    index: function (req, res) {
        User.getDatastore().sendNativeQuery("SELECT * from test.users u INNER JOIN test2.users t ON u.id=t.id limit 10",function(err, rawResult) {
            res.send(rawResult);
        })
    },

};

但这给了我一个错误:

{
   "code": "ER_NO_SUCH_TABLE",
    "errno": 1146,
    "sqlMessage": "Table 'test.users' doesn't exist",
}

另外,我有一个空白的用户模型,并且当查询类似(它使用默认数据库,即测试)时,原始 sql 查询的执行工作完美。select * from users我如何通过在sails js 中连接多个 MySQL 数据库来实现这种查询?

4

1 回答 1

0

我能够通过这种方式解决问题:

我的 config.datastore 文件:

module.exports.datastores = {
 default: {
      adapter: require('sails-mysql'),
      url: 'mysql://root:12345@192.168.0.5:3306/',
    },

};

我的控制器:

module.exports = {

    index: function (req, res) {
        User.getDatastore().sendNativeQuery("SELECT * from test.users u INNER JOIN test2.users t ON u.id=t.id limit 10",function(err, rawResult) {
            res.send(rawResult);
        })
    },

};

起初很难弄清楚,因为没有这样的示例显示使用原始 MySQL 查询时来自不同数据库的多个表的连接。

我所做的唯一更改是我刚刚从默认连接 URL 中删除了数据库名称。现在我可以访问这个特定服务器上的所有数据库,还可以加入多个数据库。

于 2019-03-15T09:06:45.810 回答