使用 Sequelize 查询自联接,包括相关记录 [英] Query self-join with Sequelize, including related record
本文介绍了使用 Sequelize 查询自联接,包括相关记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们将 Postgres 用于 Node.js 应用程序,并有一个 Sequelize 模型 Entry
,大致定义为:
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!"
如何进行此查询并从同一张表中的另一条记录中提取相关数据?
推荐答案
尝试使用您已经在关联中定义的名称传递 as
属性:
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'
}]
})
这篇关于使用 Sequelize 查询自联接,包括相关记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文