将相同模型的关系序列化

发布于 2025-02-09 16:58:46 字数 3582 浏览 4 评论 0原文

我正在创建聊天应用程序,并尝试通过友谊在用户和用户之间建立关系。到目前为止,我可以建立一个关系,但最终只有一个用户分配了一个朋友。我正在使用Express,将部署到Heroku的后期序列化。我不知道如何实现它,任何帮助都会受到赞赏

:移民: `输入代码此处`await queryInterface.createtable('users',{id:{type:datatypes.uuid,primarykey:true,defaultValue:datatypes.uidv4,}}},},},},}); await queryInterface.createTable('friendships', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, user: { type: DataTypes.UUID, allowNull: false, references: { model: '用户',键:'id'},},朋友:{type:datatypes.uuid,allownull:allyull:false,references:{model:'users',key',key:'id'},},status:{type:datatypes。 enum(“待处理”,“接受”,“拒绝”),allathull:false,defaultValue:'perdend',},});

友谊模型:

    Friendship.init(
    {
    id: {
    type: DataTypes.UUID,
    primaryKey: true,
    defaultValue: DataTypes.UUIDV4,
    },
    user: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
    model: 'users',
    key: 'id',
    },
    },
    friend: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
    model: 'users',
    key: 'id',
    },
    },
    status: {
    type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'),
    allowNull: false,
    defaultValue: 'PENDING',
    },
    },
    {
    sequelize,
    underscored: true,
    timestamps: false,
    modelName: 'friendship',
    }
    );

协会:

    User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user', 
    otherKey: 'friend' });
    Friendship.belongsTo(User, { as: 'info', foreignKey: 'friend' }); 

controler:controler:

    export const addFriend = async (req: Request, res: Response) => {
    try {
    const { friendId } = req.body;
    const userId = req.decodedToken?.id;

    const friend = await User.findByPk(friendId, {
    attributes: { exclude: ['passwordHash'] },
    include: [{ model: User, as: 'friends' }],
    });

    if (friend)
    await Friendship.create({
    user: userId,
    friend: friend.id,
    status: 'PENDING',
    });

    return res.status(200).json({ status: 'success' });
    } catch (e) {
    res.status(500).json({ error: 'The server cannot create the user' });
    console.log(e);
    }
    };

controler: wonsement:worsevy:worsement:edist:edit:edit:edit:edit:edit:edit:

    "users": {
    "count": 2,
    "rows": [
    {
    "id": "e7c7ce39-953a-45e7-a892-a5f99554382e",
    "email": "admin",
    "username": "admin",
    "name": null,
    "surname": null,
    "age": null,
    "public": true,
    "image": null,
    "friends": [
    {
    "id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
    "email": "admin2",
    "username": "admin",
    "passwordHash": "$2b$10$GajlewYeiGvUOOV08YOzLuedV/8.KJNUeHB4WPKlUFxErj91ljfWq",
    "name": null,
    "surname": null,
    "age": null,
    "public": true,
    "image": null,
    "friendship": {
    "id": "a78b9336-f5a6-4153-b3e1-e44dbe1cc7a6",
    "user": "e7c7ce39-953a-45e7-a892-a5f99554382e",
    "friend": "13029ad9-7199-47d5-bd1c-7d939b26150e",
    "status": "PENDING"
    }
    }
    ]
    },
    {
    "id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
    "email": "admin2",
    "username": "admin",
    "name": null,
    "surname": null,
    "age": null,
    "public": true,
    "image": null,
    "friends": []
    }

edit: edit: 我做了这样的东西,这不是完美的,但对我有好处

  User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user' });
  User.belongsToMany(User, { as: 'friend', through: Friendship, foreignKey: 'friend' });

I am creating a chat application and trying to create a relationship between User and User through friendship. So far I can create a relationship, but in the end only one user assigned a friend. I'm using Express, sequalize with postgress deployed to heroku. I don't know how to achieve it, any help is appreciated

migration:
`enter code here`await queryInterface.createTable('users', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, } }, }); await queryInterface.createTable('friendships', { id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4, }, user: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, friend: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'id' }, }, status: { type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'), allowNull: false, defaultValue: 'PENDING', }, });

friendship model:

    Friendship.init(
    {
    id: {
    type: DataTypes.UUID,
    primaryKey: true,
    defaultValue: DataTypes.UUIDV4,
    },
    user: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
    model: 'users',
    key: 'id',
    },
    },
    friend: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
    model: 'users',
    key: 'id',
    },
    },
    status: {
    type: DataTypes.ENUM('PENDING', 'ACCEPTED', 'DENIED'),
    allowNull: false,
    defaultValue: 'PENDING',
    },
    },
    {
    sequelize,
    underscored: true,
    timestamps: false,
    modelName: 'friendship',
    }
    );

associations:

    User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user', 
    otherKey: 'friend' });
    Friendship.belongsTo(User, { as: 'info', foreignKey: 'friend' }); 

controller:

    export const addFriend = async (req: Request, res: Response) => {
    try {
    const { friendId } = req.body;
    const userId = req.decodedToken?.id;

    const friend = await User.findByPk(friendId, {
    attributes: { exclude: ['passwordHash'] },
    include: [{ model: User, as: 'friends' }],
    });

    if (friend)
    await Friendship.create({
    user: userId,
    friend: friend.id,
    status: 'PENDING',
    });

    return res.status(200).json({ status: 'success' });
    } catch (e) {
    res.status(500).json({ error: 'The server cannot create the user' });
    console.log(e);
    }
    };

response:

    "users": {
    "count": 2,
    "rows": [
    {
    "id": "e7c7ce39-953a-45e7-a892-a5f99554382e",
    "email": "admin",
    "username": "admin",
    "name": null,
    "surname": null,
    "age": null,
    "public": true,
    "image": null,
    "friends": [
    {
    "id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
    "email": "admin2",
    "username": "admin",
    "passwordHash": "$2b$10$GajlewYeiGvUOOV08YOzLuedV/8.KJNUeHB4WPKlUFxErj91ljfWq",
    "name": null,
    "surname": null,
    "age": null,
    "public": true,
    "image": null,
    "friendship": {
    "id": "a78b9336-f5a6-4153-b3e1-e44dbe1cc7a6",
    "user": "e7c7ce39-953a-45e7-a892-a5f99554382e",
    "friend": "13029ad9-7199-47d5-bd1c-7d939b26150e",
    "status": "PENDING"
    }
    }
    ]
    },
    {
    "id": "13029ad9-7199-47d5-bd1c-7d939b26150e",
    "email": "admin2",
    "username": "admin",
    "name": null,
    "surname": null,
    "age": null,
    "public": true,
    "image": null,
    "friends": []
    }

Edit:
I made something like this, it's not perfect, but it's good for me

  User.belongsToMany(User, { as: 'friends', through: Friendship, foreignKey: 'user' });
  User.belongsToMany(User, { as: 'friend', through: Friendship, foreignKey: 'friend' });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏闹i 2025-02-16 16:58:46

请考虑许多与许多关系。

用户可以是许多用户的朋友。
许多用户可以成为一个用户的朋友。

您可能会在官方文档中找到操作方法:在这里
基本上,在两个协会中使用属于属于属性:

实施
在续集中执行此操作的主要方法如下:

  const Movie = sequelize.define('Movie',{name:datatypes.string});
const actor = sequelize.define('actor',{name:datatypes.string});
movie.belongstomany(演员,{通过:'actormovies'});
Actor.belongstomany(电影,{通过:'actormovies'});
 

Please consider a many to many relationship.

An user can be a friend of many users.
Many users can be friends of one user.

You may found the how-to implement in the official doc: here.
Basically, use belongsToMany in both associations:

Implementation
The main way to do this in Sequelize is as follows:

const Movie = sequelize.define('Movie', { name: DataTypes.STRING });
const Actor = sequelize.define('Actor', { name: DataTypes.STRING });
Movie.belongsToMany(Actor, { through: 'ActorMovies' });
Actor.belongsToMany(Movie, { through: 'ActorMovies' });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文