gpt4 book ai didi

sequelize.js - N :M association error when using include. 通过

转载 作者:行者123 更新时间:2023-12-02 03:20:45 28 4
gpt4 key购买 nike

场景

一个用户可以有多个标签对象。一个 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 对象的列表,以及用户与其关联的 Transactions 的 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 的用法不正确吗?我在其他地方的“查找”查询中成功使用了“通过”构造,但由于此“通过”嵌套在包含中,因此它的行为似乎有所不同(例如要求我显式通过.model)

如有任何帮助,我们将不胜感激!

最佳答案

重现 TypeError: Cannot call method 'replace' of undefined

你定义的 n:m 关系对我来说很好。我在 test script 中重现了 TypeError并且您对 through.where 的使用对我来说也很好(文档 here)。这可能是 Sequelize 中的错误。

解决您的问题的方法

查找用户 X 拥有的所有标签,或与用户 X 关联超过 1 个交易的一种方法是使用 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 查询使用联合。目前 Sequelize doesn't support them通过查找 API。

性能?

只看生成的 SQL,原始查询将比对 findAll 的两次调用更快。另一方面,对 findAll 的两次调用更清晰,过早的优化是愚蠢的。无论我使用哪种技术,我都会将其包装在 class method 中无论如何:)

关于sequelize.js - N :M association error when using include. 通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33596558/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com