Query self-join with Sequelize, including related record
foreign-keys, join, node.js, relationship, sequelize.js
Solution
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'
}]
})
Problem
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?