如何对两个独立的数据库使用相同的 Sequelize 模型?

问题描述 投票:0回答:2

我正在使用 Sequelize 并拥有多个具有相同表的 MySQL 数据库。每个客户一个数据库,这是为了保证每个客户的数据之间的隔离。

出于分析目的,我需要能够从多个客户数据库查询数据。我不需要加入任何桌子。

为了实现这一目标,我为每个数据库创建一个 Sequelize 实例,但是,一旦我使用第二个 Sequelize 实例

init()
模型,第一个就会被覆盖。

在下面的示例中,初始化

customerTwoStudent
后,对
customerOneStudent
的所有查询都将在客户二数据库而不是客户一数据库上运行。所以在这种情况下,
customerOneJanes
customerTwoJanes
将是相同的。

我是 Sequelize 和 Node.js 的新手,因此非常感谢您的帮助!我确定这是因为某些内容是通过引用传递的,但我不知道在哪里。

index.js

import {Sequelize} from "sequelize";

import Student from "./models/Student";

const dbHost = "";
const dbUsername = "";
const dbPasssword = "";

async function getStudents() {
  const databaseOneSequelize = new Sequelize(
    "customer01",
    dbUsername,
    dbPassword,
    {host: dbHost, dialect: "mysql", dialectOptions: {ssl: "Amazon RDS"}},
  );

  const databaseTwoSequelize = new Sequelize(
    "customer02",
    dbUsername,
    dbPassword,
    {host: dbHost, dialect: "mysql", dialectOptions: {ssl: "Amazon RDS"}},
  );

  const customerOneStudent = Student.init(databaseOneSequelize);
  const customerTwoStudent = Student.init(databaseTwoSequelize);

  const customerOneJanes = await customerOneStudent.findAll({where: {firstName: "Jane"}});
  const customerTwoJanes = await customerTwoStudent.findAll({where: {firstName: "Jane"}});
}

模型/Student.js

import {DataTypes, Model} from "sequelize";

export default class Student extends Model {
  static init(sequelize) {
    const attributes = {
      firstName: DataTypes.STRING,
      lastName: DataTypes.STRING,
    };

    const options = {
      underscored: true,
    };

    return super.init(attributes, {sequelize, ...options});
  }
}
node.js sequelize.js
2个回答
0
投票

我对sequelize的理解是,它使用其默认查询方法一次只能查询一个数据库(最后初始化的)。

要查询不同的数据库,您可以使用原始查询并指定替换数据库:

const { QueryTypes } = require('sequelize')

let dbToQuery = "";
let firstName = "Jane";

dbToQuery = "customer01"; // db name
const customerOneJanes = await sequelize.query('SELECT * FROM :db.student WHERE firstname = :firstName', {
  replacements: {db: dbToQuery, firstName: firstName}
  type: QueryTypes.SELECT
});

dbToQuery = "customer02";
const customerOneJanes = await sequelize.query('SELECT * FROM :db.student WHERE firstname = :firstName', {
  replacements: {db: dbToQuery, firstName: firstName}
  type: QueryTypes.SELECT
});
const customerTwoJanes

0
投票

无需使用原始查询即可实现这一点。我们正在对不同的客户数据库做类似的事情。关键是您不能使用

class X extends Model
init()
方法来定义模型,因为这会覆盖与最后一个调用的连接。

相反,您必须对每个 Sequelize 实例使用

sequelize.define()
如此处所述

databaseOneSequelize.define('Student', { modelFields });
databaseTwoSequelize.define('Student', { modelFields });

const customerOneJanes = await databaseOneSequelize.models.Student.findAll({where: {firstName: "Jane"}});
const customerTwoJanes = await databaseTwoSequelize.models.Student.findAll({where: {firstName: "Jane"}});
© www.soinside.com 2019 - 2024. All rights reserved.