node.js - Sequelize 包含多态关系的相关项

标签 node.js sequelize.js

来自docs我们有一个与 ImagePost 具有多态关系的 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? (可以是 PostImage)

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/

相关文章:

node.js - express中404和500错误的正确处理方式

javascript - 我的自定义 JavaScript 函数是 "not a function"?

node.js - NodeJS + EJS + Promise : page is not displayed until the promise is fulfilled

javascript - 为什么当我编写array.map,foreach或简单的for时,它在Electron + Javascript中异步运行?

node.js - 使用 pg-promise 插入多条记录

mysql - 使用 Sequelize 和 MySQL 的地理空间距离计算器

sequelize.js - 如何在 Sequelize 中添加用户是否存在或新用户的属性?

node.js - 如何填充 Sequelize 关联 - 已编辑

sequelize.js - sequelize 使用外键创建记录

sql - 如何使用postgres获取日期