【发布时间】:2015-01-06 09:21:32
【问题描述】:
我有一个名为 Org 的 Sequelize 对象,它代表存储在 MySQL 中的组织表中的一行。此表具有存储为 16 字节 varbinary 的 UUID 主键 (id)。如果我的 JavaScript 代码中有一个对象的 UUID (bfaf1440-3086-11e3-b965-22000af9141e) 作为字符串,那么在 Sequelize 的 where 子句中将它作为参数传递的正确方法是什么?
以下是我尝试过的选项
模型:(对于现有的 MySQL 表)
var uuid = require('node-uuid');
module.exports = function(sequelize, Sequelize) {
return sequelize.define('Org', {
id: {
type: Sequelize.BLOB, //changing this to Sequelize.UUID does not make any difference
primaryKey: true,
get: function() {
if (this.getDataValue('id')) {
return uuid.unparse(this.getDataValue('id'));
}
}
},
name: Sequelize.STRING,
}, {
tableName: 'organisation',
timestamps: false,
}
});
};
选项 1:使用 node-uuid 将 UUID 作为字节缓冲区传递
Org.find({
where: {
id: uuid.parse(orgId)
}
}).then(function(org) {
success(org);
}).catch(function(err) {
next(err);
});
Executing (default): SELECT `id`, `name` FROM `Organisation` AS `Org`
WHERE `Org`.`id` IN (191,175,20,64,48,134,17,227,185,101,34,0,10,249,20,30);
Sequelize 将字节缓冲区视为多个值,因此我得到多个匹配项并返回最顶部的记录(不是具有正确 UUID 的记录)。
选项 2:编写原始 SQL 查询并将 UUID 作为 HEX 值传递
sequelize.query('SELECT * from organisation where id = x:id', Org, {plain: true}, {
id: orgId.replace(/-/g, '')
}).then(function(org) {
success(org);
}).catch(function(err) {
next(err);
});
Executing (default): SELECT * from organisation
where id = x'bfaf1440308611e3b96522000af9141e'
我得到了正确的记录,但这种方法并不是很有用,因为我在数据库中有更复杂的关系,并且手动编写太多查询超出了 ORM 的目的。
我正在使用 Sequelize 2.0.0-rc3。
【问题讨论】:
-
请同时显示您的模型定义。你的 id 字段在你的模型中定义为二进制吗?
标签: mysql node.js uuid sequelize.js