我们将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)));
我收到错误:“条目与条目无关!”
How can I do this query and pull through this related data from another record in the same table?
1 回答
尝试使用您在关联中定义的名称传递
as
属性: