如何在Sequalize PostgreSQL中根据用户ID分组数据?

时间:2018-12-07 07:01:14

标签: postgresql group-by include sequelize.js

我想将某些用户的所有消息分组在一个数组中。我该如何实现?我有近200个用户,我想将每个用户的对话以及用户详细信息显示在单独的数组中。

  

聊天表具有收件人ID,发件人消息,created_at和Updated_at。

我已经尝试过了,但是它会返回消息以及发件人详细信息:

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

所需的输出:

[
  {
    "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"
        },
        {...},
        {...}
      ]  
  },
]

聊天模式:

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

用户模型:

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

1 个答案:

答案 0 :(得分:0)

您可以使用:

获得所需的输出。
models.User.findAll({ 
    where : { id : USER_ID },
    include: [
        {
            model:models.chat,
            required : false ,
            where : {
                $or : [ { senderId : USER_ID } , { recipientId : USER_ID }]
            }
        }
    ]
});
  

注意:

     

您可以通过删除required : false ,进行检查,因为我尚未测试   代码。