does seauelize support self reference tables?
For example, if I have a table called product, and logically, it has child / parent relationships with its self, so I defined a parent_id column that has a fk to another record in the same products table
Is this possible? How should the associations be set up?
Thanks!
It's quite possible even though you won't get the possibility to load the whole tree by using Sequelize and only the direct children records or the direct parent by including them in the query:
Product.belongsTo(Product, { foreignKey: 'parentId', as: 'Parent' });
Product.hasMany(Product, { foreignKey: 'parentId', as: 'Children' });
...
const parentWithChildren = await Product.findAll({
where: {
id: productId
},
include: [{
model: Product,
as: 'Children'
}]
})
const childrenWithParents = await Product.findAll({
where: {
<some children conditions here>
},
include: [{
model: Product,
as: 'Parent'
}]
})