在sequelize中动态定义数据库以支持多租户返回错误的查询语法

35g0bw71  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(474)

我正在使用共享数据库隔离模式原理开发多租户应用程序(saas)。
我试过从https://github.com/renatoargh/data-isolation-example
从这篇文章https://renatoargh.wordpress.com/2018/01/10/logical-data-isolation-for-multi-tenant-architecture-using-node-express-and-sequelize/
这是我使用schema选项的sequelize模型

module.exports = (sequelize, DataTypes) => {
  const Task = sequelize.define('Task', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      field: 'Id'
    },

    description: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'Description'
    },

    done: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      default: false,
      field: 'Done'
    },

    taskTypeId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: 'TaskTypeId'
    },

    userId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: 'UserId'
    }
  }, {
      freezeTableName: true,
      tableName: 'Tasks',
      createdAt: false,
      updatedAt: false
    })
  Task.changeSchema = schema => Task.schema(schema)
  Task.associate = models => {
    Task.belongsTo(models.TaskType, {
      as: 'taskType',
      foreignKey: 'taskTypeId'
    })
  }

  return Task
}

别再提这个问题了

SELECT
  `Task`.`Id`              AS `id`,
  `Task`.`Description`     AS `description`,
  `Task`.`Done`            AS `done`,
  `Task`.`TaskTypeId`      AS `taskTypeId`,
  `Task`.`UserId`          AS `userId`,
  `taskType`.`Id`          AS `taskType.id`,
  `taskType`.`Description` AS `taskType.description`
FROM `tenant_1.Tasks` AS `Task` LEFT OUTER JOIN `shared.TaskTypes` AS `taskType`
    ON `Task`.`TaskTypeId` = `taskType`.`Id`
WHERE `Task`.`UserId` = 1;

如您所见,mysql中的“tenant_1.tasks”是一个错误的语法。它必须来自“租户\u 1”。tasks
如何将“tenant\u 1.tasks”更改为“tenant\u 1”。“tasks”`

wwtsj6pe

wwtsj6pe1#

你在用mysql吗?如果是这样,那就是预期的行为。
从model.schema的文档中:
将架构应用于此模型。对于postgres,这实际上会将架构放在表名前面- "schema"."tableName" ,而架构将在mysql和sqlite的表名之前- 'schema.tablename' .

相关问题