来自docs我们有一个与 Image
和 Post
具有多态关系的 Comment
模型:
this.Comment = this.sequelize.define('comment', {
title: Sequelize.STRING,
commentable: Sequelize.STRING,
commentable_id: Sequelize.INTEGER
});
this.Comment.prototype.getItem = function() {
return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)]();
};
this.Post.hasMany(this.Comment, {
foreignKey: 'commentable_id',
constraints: false,
scope: {
commentable: 'post'
}
});
this.Comment.belongsTo(this.Post, {
foreignKey: 'commentable_id',
constraints: false,
as: 'post'
});
this.Image.hasMany(this.Comment, {
foreignKey: 'commentable_id',
constraints: false,
scope: {
commentable: 'image'
}
});
this.Comment.belongsTo(this.Image, {
foreignKey: 'commentable_id',
constraints: false,
as: 'image'
});
现在,如何获取包含相关可评论项目的Comment
? (可以是 Post
或 Image
)
Comment.findOne({
where: {title: 'sequelize'},
include: ['commentable'] // what should be here?
});
最佳答案
来自 doc
The getItem utility function on Comment completes the picture - it simply converts the commentable string into a call to either getImage or getPost, providing an abstraction over whether a comment belongs to a post or an image. You can pass a normal options object as a parameter to getItem(options) to specify any where conditions or includes.
引用主题Sequelize ORM: polymorphic associations 1:m possible? 。我希望这对您有所帮助。
关于node.js - Sequelize 包含多态关系的相关项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46077566/