查找具有特定关联的所有人,并对Sequelize中的所有* other *关联人进行汇总

时间:2018-10-10 02:16:36

标签: javascript sql sqlite sequelize.js

好的,所以我将Sequelize与sqlite一起使用,以通过websockets构建实时投票系统。架构:

const Connection = sequelize.define("connection", {
    socketId: {
        type: Sequelize.UUID,
        primaryKey: true
    },
    name: { type: Sequelize.STRING, unique: true, allowNull: false }
});

const Vote = sequelize.define("vote", {
    postId: {
        type: Sequelize.UUID,
        primaryKey: true,
        onDelete: "CASCADE"
    },
    socketId: {
        type: Sequelize.UUID,
        primaryKey: true,
        onDelete: "CASCADE"
    },
    vote: {
        type: Sequelize.INTEGER,
        allowNull: false,
        validate: {
            isIn: [[-1, 1]]
        }
    }
});

Vote.belongsTo(Connection, { foreignKey: "socketId" });

const Post = sequelize.define("post", {
    id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true
    },
    content: { type: Sequelize.STRING, allowNull: false }
});

Post.belongsTo(Connection, {
    foreignKey: "authorSocketId",
    onDelete: "CASCADE"
});

Post.hasMany(Vote);

当一个客户端断开连接时,我会更新所有其他客户端,删除哪些帖子。

当客户断开连接时,我需要总结客户投票的每条帖子的票数,然后将更新后的投票数发送给客户。但是问题是我需要排除与投票总数断开连接的客户端。这是我想出的,但这似乎过于复杂:

Post.findAll({
  attributes: [
      "id",
      [
          literal(
              // Sum up all the votes not by the disconnecting client
              `(SELECT SUM("votes"."vote") FROM votes WHERE "votes"."postId"="post"."id" AND "votes"."socketId"!=$1 )`
          ),
          "upvotes"
      ]
  ],
  bind: [disconnectedSocketId],
  where: {
      // Post must not be by the disconnecting client
      authorSocketId: { [Op.ne]: disconnectedSocketId }
  },
  include: [
      {
          // Post must be voted on by the disconnecting client
          model: Vote,
          required: true,
          where: {
              socketId: disconnectedSocketId
          }
      }
  ]
}).then(posts => {
  // Once I have all the posts and their sums I update all the clients
});

所以这是我的问题。是否有一种更优雅的方法来查找断开连接的客户投票的所有帖子并汇总其所有票数,同时排除断开连接的客户的投票。

我还是SQL和关系数据库的新手,所以如果您有任何其他建议将不胜感激。

0 个答案:

没有答案