gpt4 book ai didi

javascript - Sequelize 多对多自关联

转载 作者:行者123 更新时间:2023-12-03 22:17:24 25 4
gpt4 key购买 nike

我正在尝试创建一个与自身多对多关联的模型 Users,以允许用户关注其他用户。在一个查询中,我想检索当前用户后跟的 Users;在另一个查询中,我想检索关注当前用户的人员。

这是我的 Users 模型:

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;
};

我声明 UsersUsers ,以防万一我需要在那里添加任何字段:
module.exports = (sequelize, Sequelize) => {
const UsersUsers = sequelize.define(
'UsersUsers',
{}
);
UsersUsers.associate = function(models) {};

return UsersUsers;
};

然后我查询 Users 为:
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));
});

我得到了这个结果:
{
"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
}
}
]
}
}

现在的问题:
  • 在我当前的查询中,如何从结果中排除“UsersUsers”? attributes: { exclude: ['UsersUsers'] } 不起作用...
  • 如何创建查询来检索当前用户及其关注的用户而不是他关注的用户?

  • 谢谢!

    ——
    编辑:

    问题 1. 的解决方案是将 through: { attributes: [] } 添加到包含的模型中:
    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));
    });

    还在等待问题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);
    });

    我不确定这是否行得通,仍然尝试解决这个问题,并让我知道这是否有效,或者您是否找到了任何解决方案。

    关于javascript - Sequelize 多对多自关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55208742/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com