mysql - 在 Sequelize 中动态定义数据库以支持多租户返回错误的查询语法
问题描述
我正在使用共享数据库隔离架构原则开发多租户应用程序 (SAAS)。
我已经尝试过https://github.com/renatoargh/data-isolation-example的解决方案
这是使用模式选项的我的 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 中的FROM `tenant_1.Tasks`是错误的语法。它必须来自`tenant_1`。`Tasks`
如何将`tenant_1.Tasks`更改为`tenant_1`.`Tasks`
解决方案
你在使用 MySQL 吗?如果是这样,那是预期的行为。
从Model.schema的文档中:
将模式应用于此模型。对于 postgres,这实际上会将架构放在表名前面 -
"schema"."tableName"
,而架构将添加到 mysql 和 sqlite 的表名之前 -'schema.tablename'
。
推荐阅读
- microsoft-graph-api - Microsoft Graph findMeetingTimes 终结点不起作用
- react-native - 无法在 React-Native 项目上运行“npm install”
- json - 如何使用 JSON 为 Google Cloud Storage 设置自定义元数据?
- java - 如何在java中找到实现接口的所有子类?
- mule - 我可以在不重启 Mule 的情况下重启 ActiveMQ 吗?
- excel - Trim 函数和 WorksheetFunction.Trim 不会删除前导或尾随空格
- python - 在破折号中,选择单个单选按钮时,如何使用回调更新图形?
- python - 线性回归模型(使用梯度下降)不收敛于波士顿住房数据集
- reverse-proxy - Firebase 托管是否需要反向代理?
- c - 如何像 Linux 命令 ls 一样格式化输出以打印