问题
Hello my problems is that I only want to fetch the last topic for the 'last_...'. A simple order_by won't work seeing as it will sort the forums as well, which I don't want. The code I have so far. I am doing this in CodeIgniter's built in Active Records.
return $this->db->select('forums.*,')
->select('Count(topics.id) threads, Count(replies.id) replies')
->select('topics.url last_post_url, topics.name last_post_name, topics.created last_post_date')
->select('users.url user_url, users.name user_name, ranks.name user_rank')
->from('forums')
->join('topics', 'topics.f_id = forums.id', 'left')
->join('replies', 'replies.t_id = topics.id', 'left')
->join('users', 'users.id = topics.a_id', 'left')
->join('ranks', 'users.status = ranks.id','left')
->group_by('forums.id')
->get()
->result();
In case it isn't clear what I am trying to do; I want it to get the forums, in every row I want it to add the number or topics (working), the number of replies (working), and the who the last post was made by.
Raw query
SELECT `forums`.*, Count(topics.id) threads, Count(replies.id) replies, `users`.`url` user_url, `users`.`name` user_name, `ranks`.`name` user_rank
FROM (`forums`)
LEFT JOIN `topics` ON `topics`.`f_id` = `forums`.`id`
LEFT JOIN `replies` ON `replies`.`t_id` = `topics`.`id`
LEFT JOIN `users` ON `users`.`id` = `topics`.`a_id`
LEFT JOIN `ranks` ON `users`.`status` = `ranks`.`id`
GROUP BY `forums`.`id`
回答1:
I think you need to use result_array()
instead of result()
. I might be wrong but that's how I'd do.
Also, what I'd recommend you to do is to create the SQL request with PHPMyAdmin or whatever you use so you can actually see what you get with the request, and then "translate" it to CodeIgniter syntax.
回答2:
Have you tried $row = $query->last_row() as on the User Guide: http://codeigniter.com/user_guide/database/results.html
来源:https://stackoverflow.com/questions/11619861/codeigniter-active-records-class