使用 SequelizeJs 获取父类别对象
Getting parent category object with SequelizeJs
我有一个模型定义为:
var Post = sequelize.define("Post", {
title: DataTypes.STRING,
description: DataTypes.TEXT
}, {
classMethods: {
associate: function (models) {
Post.belongsTo(models.Category, {as: 'category', foreignKey:'categoryId'});
}
}
});
然后类别模型为:
var Category = sequelize.define("Category", {
code: DataTypes.STRING,
description: DataTypes.STRING,
img: DataTypes.STRING,
}, {
classMethods: {
associate: function (models) {
Category.hasOne(models.Category, {as: 'parent', foreignKey: 'parentId'});
}
}
});
如您所见,post属于一个类别,可以是父类别或子类别。
每个类别只能有一个父类别。
现在我想要的是获取父类别(如果存在)。我可以去N号级别。但是我很高兴,如果它只在一个级别上工作,即
类别 - 职位
子类别 - IT
现在,当我有一个属于 IT 的 post 时,我想获取 IT 类别对象,但同时 IT 类别对象必须有另一个类别作业记录对象。
目前我只能得到子类别:
app.db.sequelize.models.Post.findAll({
where: ['"Post".id = ?', postId],
include: [
{model: app.db.sequelize.models.Category, as: 'category'},
]
}).then(function (post) {
res.send({post: post});
})
Post.findAll({
where: ['"Post".id = ?', postId],
include: [
{
model: Category,
as: 'category',
include: [
{ model: Category, as: 'parent' }
]
},
]
});
我有一个模型定义为:
var Post = sequelize.define("Post", {
title: DataTypes.STRING,
description: DataTypes.TEXT
}, {
classMethods: {
associate: function (models) {
Post.belongsTo(models.Category, {as: 'category', foreignKey:'categoryId'});
}
}
});
然后类别模型为:
var Category = sequelize.define("Category", {
code: DataTypes.STRING,
description: DataTypes.STRING,
img: DataTypes.STRING,
}, {
classMethods: {
associate: function (models) {
Category.hasOne(models.Category, {as: 'parent', foreignKey: 'parentId'});
}
}
});
如您所见,post属于一个类别,可以是父类别或子类别。
每个类别只能有一个父类别。
现在我想要的是获取父类别(如果存在)。我可以去N号级别。但是我很高兴,如果它只在一个级别上工作,即
类别 - 职位 子类别 - IT
现在,当我有一个属于 IT 的 post 时,我想获取 IT 类别对象,但同时 IT 类别对象必须有另一个类别作业记录对象。
目前我只能得到子类别:
app.db.sequelize.models.Post.findAll({
where: ['"Post".id = ?', postId],
include: [
{model: app.db.sequelize.models.Category, as: 'category'},
]
}).then(function (post) {
res.send({post: post});
})
Post.findAll({
where: ['"Post".id = ?', postId],
include: [
{
model: Category,
as: 'category',
include: [
{ model: Category, as: 'parent' }
]
},
]
});