Self referring foreign key in sequlize js

六眼飞鱼酱① 提交于 2019-12-13 03:48:08

问题


I have a model employee (id,first_name,last_name,manager_id)

Here the manager_id is a self refering foreign key where it refers to the id column of the same table. How do I implement such a use case in sequelize.

I tried this and this is not working

employee.belongsTo(models.employee, {
        foreignKey: 'manager_id'
      }),

回答1:


You can define association like :

employee.belongsTo(employee, {as: "Manager"});
employee.hasMany(employee, { as: "Employee", foreignKey: "manager_id", useJunctionTable: false });

And then use it like

employee.findAll({
    include : {
        model : employee ,
        as : 'Manager'
    }
})

OR

You can use sequelize-hierarchy

var employee = sequelize.define('employee', {
    name: Sequelize.STRING,
    manager_id: {
        type: Sequelize.INTEGER,
        hierarchy: true
    }
});

employee.findAll({ hierarchy: true }).then(function(results) {
    // results = [
    //  { id: 1, manager_id: null, name: 'a', children: [
    //      { id: 2, manager_id: 1, name: 'ab', children: [
    //          { id: 3, manager_id: 2, name: 'abc' }
    //      ] }
    //  ] }
    // ]
});


来源:https://stackoverflow.com/questions/53813479/self-referring-foreign-key-in-sequlize-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!