选择用户论坛活动,同时根据权限限制结果


Selecting a users forum activity while limiting results based on permission

我有一个论坛,它分为多个表:类别、主题和线程。

CREATE TABLE forum_categories (
  cat_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  role_id INTEGER UNSIGNED NOT NULL DEFAULT 0,
  cat_name VARCHAR(50) NOT NULL,
  PRIMARY KEY(cat_id),
  FOREIGN KEY (role_id)
    REFERENCES roles(role_id)
);
CREATE TABLE forum_topics (
  topic_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  cat_id INTEGER UNSIGNED NOT NULL,
  topic_name VARCHAR(50) NOT NULL,
  topic_desc VARCHAR(100) NOT NULL,
  PRIMARY KEY(topic_id),
  FOREIGN KEY (cat_id)
    REFERENCES forum_categories(cat_id)
);
CREATE TABLE forum_threads (
  thread_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  parent_id INTEGER UNSIGNED NOT NULL DEFAULT 0,
  topic_id INTEGER UNSIGNED NOT NULL,
  user_id INTEGER UNSIGNED NOT NULL,
  title VARCHAR(100) NOT NULL,
  body TEXT NOT NULL,
  create_date DATETIME NOT NULL,
  PRIMARY KEY (thread_id),
  FOREIGN KEY (parent_id)
    REFERENCES forum_threads(thread_id),
  FOREIGN KEY (topic_id)
    REFERENCES forum_topics(topic_id),
  FOREIGN KEY (user_id)
    REFERENCES users(user_id)
);

类别表有一个名为role_id的字段,如果设置为0以外的任何值,则意味着只有具有该角色的用户才能查看该类别中的主题或与之交互。

我面临的问题是,当试图将特定用户的最近活动拉到每个人面前时。我想在包含请求的user_id的线程表上COUNT(*),但我需要排除具有与受限类别相关联的topic_id的线程,除非请求信息的用户具有权限。

如果查看一个特定的线程,我会简单地提取topic_id并像这样检查:

// validate topic id and check for permission
$forum = new Forum();
$valid_topics = $forum->getTopics();
if (!array_key_exists($topic_id, $valid_topics)) {
    // invalid topic id
}
$valid_categories = $forum->getCategories();
$role_id = $valid_categories[$valid_topics[$topic_id]['cat_id']]['role_id'];
if ($role_id == 0 || array_key_exists($role_id, $session_user_roles)) {
    // user has permission
}

现在我正在尝试将我的PHP逻辑转换为SQL。以下是我想要的伪代码示例:

SELECT COUNT(*),
  (SELECT role_id,
     (SELECT cat_id
        FROM forum_topics AS t2
        WHERE topic_id = t1.topic_id) AS cat_id
     FROM forum_categories
     WHERE cat_id = t2.cat_id) AS role_id
  FROM forum_threads AS t1
  WHERE user_id = $user_id AND (role_id != 0 OR FIND_IN_SET(role_id, $session_user_roles) > 0)

有什么需要帮忙的吗?

尝试这种方式

SELECT count(*)
FROM forum_threads thr
JOIN forum_topics top    ON thr.topic_id = top.topis_id 
JOIN forum_categories fc ON top.cat_id = fc.cat_id 
WHERE thr.user_id = $user_id
    AND fc.role_id IN ( 0,     24, 55, 888, .... list of user roles ... )

在用户角色列表(最后一个条件)中,总是将0作为第一个数字,然后是他的其他角色。