Query hierarchical data structures in sql with knex
npm install knex-tree
id | parentId | desc |
---|---|---|
1 | null | I am 1 |
2 | 1 | I am 2 |
3 | 1 | I am 3 |
a | 2 | I am a |
b | 2 | I am b |
const { KnexTree } = require('knex-tree');
const knex = require('knex');
const tree = new KnexTree({
db: knex({ ... }),
table: 'mytree',
idColumn: 'id',
parentIdColumn: 'parentId',
});
const node = tree.node(5);
const data = await tree.getAllData();
const id = node.id;
const isExist = await node.isExist();
// data is null if the id doesn't exist in the table
const data = await node.getData();
// data is null if parent dosen't exist in the table
const data = await node.getParentData();
const data = await node.getChildrenData();
// return true if node is root
const data = await node.isRoot();
// return the path from root to this node
const data = await node.getPath();
// data is null if there is no data which match "id = 7" & "parentId = this.id"
const data = await node.hasChild(7);
// data is null if there is no data which match "id = 7" & "hasChild(this.id)"
const data = await node.hasParent(7);
// data is null if this is no ancestor whose id = 7
const data = await node.hasAncestor(7);
// data is null if this is no descendant whose id = 7
const data = await node.hasDescendant(7);
// data is null if this is no ancestor whose id = 7
// return the path from this node to the ancestor(id = 7)
const data = await node.getPathUpTo(7);
// data is null if this is no descendant whose id = 7
// return the path from this node to the descendant(id = 7)
const data = await node.getPathDownTo(7);
// return all descendants
let data = await node.getDescendants();
// return all descendants whose TreeLv <= 2
data = await node.getDescendants(2);
- Github: @a179346
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Give a ⭐️ if this project helped you!
Copyright © 2021 a179346.
This project is MIT licensed.
This README was generated with ❤️ by readme-md-generator