N:M 使用 include.through 时出现关联错误
N:M association error when using include.through
场景
一个用户可以有多个标签对象。一个 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'});
问题
我正在尝试 return 给定用户拥有的 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' 嵌套在包含中,它的行为似乎有所不同(例如要求我通过 through.model 明确地)
如有任何帮助,我们将不胜感激!
复制TypeError: Cannot call method 'replace' of undefined
你定义的 n:m 关系对我来说很好。我在 test script and your usage of through.where
looks fine to me as well (documentation here) 中重现了 TypeError。这可能是 Sequelize 中的错误。
解决您的问题的方法
查找用户 X 拥有的所有标签,或与用户 X 关联的 1+ t运行 操作的一种方法是使用 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 中:)
场景
一个用户可以有多个标签对象。一个 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'});
问题
我正在尝试 return 给定用户拥有的 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' 嵌套在包含中,它的行为似乎有所不同(例如要求我通过 through.model 明确地)
如有任何帮助,我们将不胜感激!
复制TypeError: Cannot call method 'replace' of undefined
你定义的 n:m 关系对我来说很好。我在 test script and your usage of through.where
looks fine to me as well (documentation here) 中重现了 TypeError。这可能是 Sequelize 中的错误。
解决您的问题的方法
查找用户 X 拥有的所有标签,或与用户 X 关联的 1+ t运行 操作的一种方法是使用 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 中:)