具有与 Sequelize 相同的 targetKey 的动态 belongsTo
Dynamic belongsTo with same targetKey with Sequelize
我想创建一个文件 table,它应该能够与其他几个 table 相关联。文件可以连接到“客户端”、“用户”、“文档”等。
我知道我可以为其中的每一个创建一个关系 table 并连接一个客户端和一个文件。但是由于最多可以有 10 种不同的方式来连接一个文件,我正在考虑只有一个关系 table 会有这些列:
file_id
resource_type
resource_id
因此,一个文件可能与“客户”相关,相关行如下所示:
file_id: 123
resource_type: 'client'
resource_id: '444'
有没有办法在 Sequelize 中实现这一点?
伪代码示例:
File.belongsTo(models.Client, {
foreignKey: 'client_id',
targetKey: 'resource_id',
where: { resource_type: 'client' } // I know this is not a thing
});
File.belongsTo(models.Document, {
foreignKey: 'document_id',
targetKey: 'resource_id',
where: { resource_type: 'document' }
});
如果有其他更好的方法来构造它,我很高兴听到。
我建议你看看Polymorphic associations。看来这就是你要找的。
我想创建一个文件 table,它应该能够与其他几个 table 相关联。文件可以连接到“客户端”、“用户”、“文档”等。 我知道我可以为其中的每一个创建一个关系 table 并连接一个客户端和一个文件。但是由于最多可以有 10 种不同的方式来连接一个文件,我正在考虑只有一个关系 table 会有这些列:
file_id
resource_type
resource_id
因此,一个文件可能与“客户”相关,相关行如下所示: file_id: 123 resource_type: 'client' resource_id: '444'
有没有办法在 Sequelize 中实现这一点? 伪代码示例:
File.belongsTo(models.Client, {
foreignKey: 'client_id',
targetKey: 'resource_id',
where: { resource_type: 'client' } // I know this is not a thing
});
File.belongsTo(models.Document, {
foreignKey: 'document_id',
targetKey: 'resource_id',
where: { resource_type: 'document' }
});
如果有其他更好的方法来构造它,我很高兴听到。
我建议你看看Polymorphic associations。看来这就是你要找的。