Closed durgadp closed 3 years ago
Did you initialize the model as a hierarchy (using Model.isHierarchy();
at time you define the model)?
If that's not the problem please (a) read the docs thoroughly (apologies if that's obvious, but lots of people do not, it seems) and (b) post a repo case here. I'll do my best to help.
// Model User
const Sequelize = require('sequelize');
require('sequelize-hierarchy')(Sequelize);
const database = require('../configs/database');
class User extends Sequelize.Model {}
User.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
parent_id: {
type: Sequelize.INTEGER,
hierarchy: true,
defaultValue: 0,
},
username: {
type: Sequelize.STRING,
allowNull: false,
},
level: {
type: Sequelize.TINYINT,
},
}, {
sequelize: database,
tableName: 'tt_user',
});
User.isHierarchy({
through: 'tt_user_ancestor',
throughTable: 'tt_user_ancestor',
throughKey: 'user_id',
foreignKey: 'parent_id',
throughForeignKey: 'parent_id',
levelFieldName: 'level',
});
module.exports = User;
// Use
let user = await User.findOne({
include: [
{
model: User,
as: 'descendents',
}
],
where: {
id: id,
}
});
// Response
{
id: 1,
parent_id: 0,
username: "userl1",
level: 1,
descendents: [
{
id: 2,
parent_id: 1,
username: "userl2",
level: 2,
tt_user_ancestor: {
user_id: 2,
parent_id: 1
}
},
{
id: 3,
parent_id: 2,
username: "userl3",
level: 3,
tt_user_ancestor: {
user_id: 3,
parent_id: 1
}
},
{
id: 4,
parent_id: 2,
username: "userl3_2",
level: 3,
tt_user_ancestor: {
user_id: 4,
parent_id: 1
}
}
]
}
Is not working to 2 level
If you're looking to get all the descendents in a tree, you need to add hierarchy: true
to the query.
let user = await User.findOne({
include: [
{
model: User,
as: 'descendents',
hierarchy: true
}
],
where: {
id: id,
}
});
Is that what you were trying to do? I don't really understand what you mean by "Is not working to 2 level".
Closing as no response by OP.
I have a model with key parent_id. I have set hierarchy: true and also added hierarchy_level column to the model. await Model.findAll({hierarchy: true }) . Model data having 3 levels of records. But it showing me the first level record or we can say how normal findAll works. Some time it's showing me an error "You cannot set hierarchy on 'Model' without using the 'descendents' accessor".