用户可以拥有许多Tag对象。 Tag对象属于一个用户。标签有很多交易。交易属于一个标签。用户有很多交易。交易可以有很多用户。
var User = sequelize.define('User', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
...
}, { timestamps: false, freezeTableName: true, tableName: 'register'});
var Tag = sequelize.define('Tag', {
tagId: {
type: Sequelize.STRING(50),
primaryKey: true,
allowNull: false
},
...
}, { timestamps: false, freezeTableName: true, tableName: 'tag'});
var Transaction = sequelize.define('Transaction', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
active: {
type: Sequelize.BOOLEAN,
defaultValue: true
}
}, { timestamps: false, freezeTableName: true, tableName: 'transaction'});
var UserTx = sequelize.define('UserTx', {
id: {
type: Sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
}
},
{ timestamps: false, freezeTableName: true, tableName: 'user_transaction'});
User.hasMany(Tag, {foreignKey: 'owner_id', foreignKeyConstraint: true});
Tag.belongsTo(User, {foreignKey: 'owner_id', foreignKeyConstraint: true});
Tag.hasMany(Transaction, {foreignKey: 'tag_id', foreignKeyConstraint: true});
Transaction.belongsTo(Tag, {foreignKey: 'tag_id', foreignKeyConstraint: true});
User.belongsToMany(Transaction, {through: {model: UserTx, unique: false}, foreignKey: 'user_id'});
Transaction.belongsToMany(User, {through: {model: UserTx, unique: false}, foreignKey: 'tx_id'});
我正在尝试返回给定用户拥有的Tag对象列表,以及用户已将事务关联起来的Tag对象。在纯SQL中:
select * from tag
left outer join transaction on tag."tagId" = transaction.tag_id
left outer join user_transaction on transaction.id = user_transaction.tx_id
where tag.owner_id = ? or user_transaction.user_id = ?
我目前的Sequelize查询:
Tag.findAll({
where: { owner_id: userId }, // missing OR user_transaction.user_id = userId
include: [{
model: Transaction,
attributes: ['id'],
through: {model: UserTx, where: {user_id: userId}, attributes: ['user_id', 'tx_id']},
where: {
active: true
},
required: false, // include Tags that do not have an associated Transaction
}]
})
调用此查询时,出现以下错误:
Unhandled rejection TypeError: Cannot call method 'replace' of undefined
at Object.module.exports.removeTicks (/site/services/node_modules/sequelize/lib/utils.js:343:14)
at Object.module.exports.addTicks (/site/services/node_modules/sequelize/lib/utils.js:339:29)
at Object.QueryGenerator.quoteIdentifier (/site/services/node_modules/sequelize/lib/dialects/postgres/query-generator.js:843:20)
at generateJoinQueries (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1207:72)
at Object.<anonymous> (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1388:27)
at Array.forEach (native)
at Object.QueryGenerator.selectQuery (/site/services/node_modules/sequelize/lib/dialects/abstract/query-generator.js:1387:10)
at QueryInterface.select (/site/services/node_modules/sequelize/lib/query-interface.js:679:25)
at null.<anonymous> (/site/services/node_modules/sequelize/lib/model.js:1386:32)
在removeTicks函数中设置断点并在's'(列名属性)上设置监视,我注意到以下内容:
s = "Transactions"
s = "Transactions.id"
s = "Transactions.undefined" // should be Transactions.UserTx ?
s = "user_id"
s = "Transactions.undefined.user_id"
s = "Transactions.undefined"
s = "tx_id"
s = "Transactions.undefined.tx_id"
我对N:M的使用是否不正确?我在其他地方的'find'查询中成功使用了'through'结构,但由于这个'through'嵌套在include中,它似乎表现得不同(例如要求我明确地传递.model)
非常感谢任何帮助!
答案 0 :(得分:1)
重现TypeError: Cannot call method 'replace' of undefined
你定义的n:m关系对我来说很好。我在test script中重现了TypeError,您对through.where
的使用对我来说也很合适(文档here)。这可能是Sequelize中的一个错误。
适用于您的问题的方法
找到用户X拥有的所有标签,或者有1个与用户X关联的事务的一种方法是使用2次调用findAll然后重复删除结果:
function using_two_findall(user_id) {
var tags_associated_via_tx = models.tag.findAll({
include: [{
model: models.transaction,
include: [{
model: models.user,
where: { id: user_id }
}]
}]
});
var tags_owned_by_user = models.tag.findAll({
where: { owner_id: user_id }
});
return Promise.all([tags_associated_via_tx, tags_owned_by_user])
.spread(function(tags_associated_via_tx, tags_owned_by_user) {
// dedupe the two arrays of tags:
return _.uniq(_.flatten(tags_associated_via_tx, tags_owned_by_user), 'id')
});
}
另一种方法是使用您建议的原始查询:
function using_raw_query(user_id) {
var sql = 'select s05.tag.id, s05.tag.owner_id from s05.tag ' +
'where s05.tag.owner_id = ' + user_id + ' ' +
'union ' +
'select s05.tag.id, s05.tag.owner_id from s05.tag, s05.transaction, s05.user_tx ' +
'where s05.tag.id = s05.transaction.tag_id and s05.user_tx.tx_id = s05.transaction.id and ' +
's05.user_tx.user_id = ' + user_id;
return sq.query(sql, { type: sq.QueryTypes.SELECT})
.then(function(data_array) {
return _.map(data_array, function(data) {
return models.tag.build(data, { isNewRecord: false });;
});
})
.catch(function(err) {
console.error(err);
console.error(err.stack);
return err;
});
}
您可以在此答案中看到上面链接的测试脚本中的两种技术。
快速说明您可以看到我的原始查询与您的查询略有不同。当我运行它时,它没有生成与问题描述相匹配的输出。另外,作为另一个快速说明,我的原始SQL查询使用了一个联合。通过查找API续作目前doesn't support them。
<强>性能吗
只要查看生成的SQL,原始查询就会比对findAll的两次调用更快。另一方面,对findAll的两次调用更清晰,过早的优化是愚蠢的。无论我使用哪种技术,我都会将其包裹在class method中:)