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

时间:2013-08-03 23:34:32

标签: php mysql

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

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以外的任何值,则表示只允许具有该角色的用户查看该类别中的主题或与之交互。< / p>

我遇到的问题是尝试拉取特定用户最近的活动供所有人查看。我想在包含所请求的COUNT(*)的线程表上user_id,但我需要排除具有与受限类别相关联的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)

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

试试这种方式

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作为第一个数字,然后是其余的角色。