Mysql
 sql >> Database >  >> RDS >> Mysql

Chiave esterna autoreferenziale in sequlize js

Puoi definire un'associazione come :

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

E poi usalo come

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

O

Puoi utilizzare 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' }
    //      ] }
    //  ] }
    // ]
});