简体   繁体   中英

Sequelize many-to-many self association

I am trying to create a model Users with many-to-many association to itself to allow users to follow another users. In one query I want to retrieve the Users followed by the current user; in another query I want to retrieve the people that follows the current user.

This is my Users model:

module.exports = (sequelize, Sequelize) => {
    const Users = sequelize.define(
        'Users',
        {
            id: {
                type: Sequelize.INTEGER,
                autoIncrement: true,
                primaryKey: true,
            },

            name: {
                type: Sequelize.STRING,
            },
        },
    );
    Users.associate = function(models) {
        Users.belongsToMany(Users, { as: 'following', through: models.UsersUsers });
    };

    return Users;
};

I declare UsersUsers , just in case I need to add any field there:

module.exports = (sequelize, Sequelize) => {
    const UsersUsers = sequelize.define(
        'UsersUsers',
        {}
    );
    UsersUsers.associate = function(models) {};

    return UsersUsers;
};

Then I query Users as:

models.Users.findOne({
    where: {
        id: req.params.id,
    },
    include: [
        {
            model: models.Users,
            as: 'following',
        },
    ],
})
    .then((results) => {
        return res.send({
            User: results,
        });
    })
    .catch((error) => {
        return res.send(String(error));
    });

And I get this result:

{
    "User": {
        "id": 1,
        "name": "User1",
        "following": [
            {
                "id": 2,
                "name": "User2",
                "UsersUsers": {
                    "UserId": 1,
                    "followingId": 2
                }
            },
            {
                "id": 3,
                "name": "User3",
                "UsersUsers": {
                    "UserId": 1,
                    "followingId": 3
                }
            },
            {
                "id": 4,
                "name": "User4",
                "UsersUsers": {
                    "UserId": 1,
                    "followingId": 4
                }
            }
        ]
    }
}

Now the questions:

  1. In my current query, how do I exclude "UsersUsers" from the result? attributes: { exclude: ['UsersUsers'] } did not work…

  2. How do I create a query to retrieve the current user with the users that follows him instead of the users followed by him?

Thanks!

-- EDIT:

The solution for the question 1. is to add through: { attributes: [] } to the included model:

models.Users.findOne({
    where: {
        id: req.params.id,
    },
    include: [
        {
            model: models.Users,
            as: 'following',
            through: {
                attributes: [],
            },
        },
    ],
})
    .then((results) => {
        return res.send({
            User: results,
        });
    })
    .catch((error) => {
        return res.send(String(error));
    });

Still pending question 2!

Users.findAll({
        include: [
    {
        model: models.Users,
        as: 'following',
        through: {
            attributes: [],
        },
    },
],
    where : {
        id : [connection.literal(` write raw sql query to get followingId here`)]
    }
})
.then(result => {
    res.json(result);
}).catch(error=>{
    res.json(error);
});

I'm not sure if this gonna work, still play around this and do let me know if this worked or if you found any solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM