查询与Sequelize的自我加入,包括相关记录 [英] Query self-join with Sequelize, including related record

查看:158
本文介绍了查询与Sequelize的自我加入,包括相关记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用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: =>新日期()
}
/ * ...更多字段在这里,等等,等等... * /
},{
classMethods:{
associate:(models)=> {
entriesModel.hasOne(models.Entry,{
onDelete:'CASCADE',
foreignKey:{
name:'parent_id',
allowNull:true
},
为:'ParentEntry'
});
}
}
}
);

基本上,一个条目可能有相应的父条目。我想检索所有条目,并通过他们的父条目,但是当我尝试:

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

.then(entry => Promise.resolve (错误)));

我得到错误:Entry不与Entry相关联

我怎样才能做这个查询,并从同一个表中的另一个记录拉动这个相关的数据?

解决方案

尝试将作为属性传递给您已经在关联中定义的名称:

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


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?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆