[eluser]sybrex[/eluser]
I have four tables in my database (simplified them a little):
Code:
CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`login` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `posts` (
`id` int(11) NOT NULL auto_increment,
`author` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `comments` (
`id` int(11) NOT NULL auto_increment,
`post` int(11) NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `votes` (
`id` int(11) NOT NULL auto_increment,
`post_type` tinyint(1) NOT NULL,
`post_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`vote` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
)
Field post_type = 0 if it is a vote for a post, 1 - a vote for comment.
User can vote only once for post and for comment and is not allowed to vote for his own posts and comments.
I am making the array of comments to the posts to display them in the view later:
Code:
$comments = array(
'id' => comment_id,
'user' => comment_author,
'text' => comment_body,
'can_vote' => TRUE/FALSE if the logined user can vote for this comment);
So, I'm looking for a better solution:
1) Get all votes of specified user in the $votes = array(comment1_ID, comment2_ID, ...) and then do something like this:
Code:
foreach ($comments as $key => $comment)
{
$comments[$key]['can_vote'] = (in_array($comment['id'], $votes) OR $comment['user'] == $logined_user_id) ? FALSE : TRUE;
}
2) Cycle through all comments and make a query to database for each comment like this:
Code:
foreach ($comments as $key => $comment)
{
$this->db->where(array('post_type' => 1, 'user_id' => $logined_user_id, 'post_id' => $current_post));
$n = $this->db->count_all_results('votes');
$comment['$key']['can_vote'] = $n == 1 ? FALSE : TRUE
}
The table of votes can be really big, and I don't know what variant would be better, faster. If you could propose other variants it would be great too.
Thank you!