Query self-join with Sequelize, including related record

十年热恋 提交于 2019-12-24 08:35:08

问题


We're using Postgres for a Node.js app and have a Sequelize model Entry which is roughly defined as:

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'
                });
            }
        }
    }
);

Basically, an entry may have a corresponding parent entry. I want to retrieve all of the entries and pull through their parent entries, but when I try:

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)));

I get the error: "Entry is not associated to Entry!"

How can I do this query and pull through this related data from another record in the same table?


回答1:


Try to pass as property with name that you already defined in the association:

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


来源:https://stackoverflow.com/questions/40294776/query-self-join-with-sequelize-including-related-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!