How to make a relationship with two items from the same table in Sequelize?

Asked

Viewed 1,002 times

-1

I have a table that holds two user Ids. The UserId and the ResponsibleId, both take from the table User.

Model:

module.exports = (sequelize, DataTypes) => {
    const Table = sequelize.define(
        'Table',
        {
            UserId: {
                type: DataTypes.INTEGER,
                allowNull: false,
                references: {
                    model: 'User',
                    key: 'id'
                },
                onUpdate: 'CASCADE',
                onDelete: 'CASCADE'
            },
            ResponsibleId: {
                type: DataTypes.INTEGER,
                allowNull: false,
                references: {
                    model: 'User',
                    key: 'id'
                },
                onUpdate: 'CASCADE',
                onDelete: 'CASCADE'
            }
        }
    );

    Table.associate = models => {
        Table.hasOne(models.User, {
            foreignKey: 'id',
            sourceKey: 'UserId',
            as: 'user'
        });
        Table.hasOne(models.User, {
            foreignKey: 'id',
            sourceKey: 'ResponsibleId',
            as: 'responsible'
        });
    };

    return Table;
};

And the User table:

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define(
        'User',
        {
            fullName: {
                type: DataTypes.STRING,
                allowNull: false
            }
        },
    );

    User.associate = models => {
        User.belongsTo(models.Table, {
            foreignKey: 'id',
            sourceKey: 'UserId'
        });
        User.belongsTo(models.Table, {
            foreignKey: 'id',
            sourceKey: 'ResponsibleId'
        });
    };

    return User;
};

But when I try to accomplish the include in query, only returns the last pointed relationship (Responsible).

{
    model: User,
    as: 'responsible'
},
{
    model: User,
    as: 'user'
}

How can I make for that query include the data of the two Ids in the search result?

I tried using hasMany but I do not know how to separate the ID’s (one pointing to user and the other responsible) in the query and the result comes the same only inside an array...

1 answer

0


I got....

In Users makes associations so:

User.associate = models => {
    User.belongsToMany(models.Table, {
        through: 'UserTable',
        foreignKey: 'UserId'
    });
    User.belongsToMany(models.Table, {
        through: 'ResponsibleTable',
        foreignKey: 'ResponsibleId'
    });
};

And on the table:

Table.associate = models => {
    Table.hasMany(models.User, {
        foreignKey: 'id',
        sourceKey: 'ResponsibleId'
    });
    Table.hasMany(models.User, {
        foreignKey: 'id',
        sourceKey: 'UserId'
    });
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.