使用 Sequelize 查询自连接,包括相关记录

Query self-join with Sequelize, including related record

我们将 Postgres 用于 Node.js 应用程序,并有一个 Sequelize 模型 Entry,其大致定义为:

const entriesModel = sequelize.define('Entry',
    {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        post_date: {
            type: DataTypes.DATE,
            allowNull: false,
            defaultValue: () => new Date()
        }
        /* ...more fields here, etc, etc... */
    }, {
        classMethods: {
            associate: (models) => {
                entriesModel.hasOne(models.Entry, {
                    onDelete: 'CASCADE',
                    foreignKey: {
                        name: 'parent_id',
                        allowNull: true
                    },
                    as: 'ParentEntry'
                });
            }
        }
    }
);

基本上,一个条目可能有一个对应的父条目。我想检索所有条目并查看它们的父条目,但是当我尝试时:

return models.Entry.findById(id, {
    include: [
        {
            model: models.Entry,
            where: {
                parent_id: id
            }
        }
    ]
})
.then(entry => Promise.resolve(cb(null, entry)))
.catch(error => Promise.resolve(cb(error)));

我收到错误:"Entry is not associated to Entry!"

如何执行此查询并从同一 table 中的另一条记录中提取相关数据?

尝试使用您已在关联中定义的名称传递 as 属性:

return models.Entry.findById(id, {
    include: [{
        model: models.Entry,
        as: 'ParentEntry'
    }]
})