简体   繁体   中英

How to group data based on user id in sequalize PostgreSQL?

I want to group all of some user's messages in one array. How can I achieve that? I have nearly 200 users and I would like to display each user's conversation in a separate array along with user details.

chat table has recipientId, senderId message, created_at & updated_at.

I have tried this, but it returns messages along with senders details:

models.chat.findAll({ include: [
      {
        model:models.User,
        as: 'User'
      }
    ],
    order: [['senderId ']],
});

Desired output:

[
  {
    "id": 5,
    "username": "username",
    "email": "username@gmail.com.com",
    "password": "o15G8DdMqRE0Ksm",
    "created_at": "2018-12-07T05:46:05.590Z",
    "updated_at": "2018-12-07T05:46:05.590Z"
    "messages":
      [
        {
          "id": 5,
          "message": "hi",
          "senderId ": 1,
          "recipientId": 5,
          "created_at": "2018-12-07T05:53:48.229Z",
          "updated_at": "2018-12-07T05:53:48.229Z",
        },
        { 
          "id": 7,
          "message": "how are you",
          "senderId ": 5,
          "recipientId": 1,
          "created_at": "2018-12-07T05:53:48.229Z",
          "updated_at": "2018-12-07T05:53:48.229Z"
        },
        {...},
        {...}
      ]  
  },
]

model of chat:

 chat.associate = (models) => {
    chat.belongsTo(models.User, {
      foreignKey: 'senderId',
      onDelete: 'CASCADE'
    });
    chat.belongsTo(models.User, {
      foreignKey: 'recipientId',
      onDelete: 'CASCADE'
    });
  };

user model:

      const User = sequelize.define('User', {
    username: {
      type: DataTypes.STRING
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {
    underscored: true,
    freezeTableName: true,
    tableName: 'users',
    hooks: {
      beforeCreate: beforeCreate,
      beforeBulkUpdate: beforeBulkUpdate
    }
  });
 User.associate = (models) => {
User.hasMany(models.Message, {
  foreignKey: 'fromUserId',
  as: 'messages'
});
User.hasMany(models.Message, {
  foreignKey: 'toUserId',
  as: 'messagess'
});
};

You can achieve the desired output with :

models.User.findAll({ 
    where : { id : USER_ID },
    include: [
        {
            model:models.chat,
            required : false ,
            where : {
                $or : [ { senderId : USER_ID } , { recipientId : USER_ID }]
            }
        }
    ]
});

NOTE :

You can check by removing required : false , as I have not tested the code.

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