Reputation: 6252
I have a forum split into multiple tables: categories, topics and threads.
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)
);
The category table has a field named role_id
, which if set to any value other than 0
means that only users with that role are allowed to view or interact with the topics in that category.
The problem I'm facing is when attempting to pull a specific users recent activity for everyone to see. I want to COUNT(*)
on the threads table containing the requested user_id
, but I need to exclude threads having a topic_id associated with a restricted category unless the user requesting the information has permission.
If viewing a specific thread, I would simply extract the topic_id
and check like this:
// 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
}
Now I'm trying to convert my PHP logic into SQL. Here is a pseudo-code example of what I'm after:
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)
Any help, please?
Upvotes: 0
Views: 30
Reputation: 36107
Try this way
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 ... )
In the list of user roles (last condition) always put 0 as a first number, then the rest of his roles.
Upvotes: 1