CodeIgniter Forums
Sort results by number of using - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Sort results by number of using (/showthread.php?tid=49978)



Sort results by number of using - El Forum - 03-09-2012

[eluser]someone Smile[/eluser]
Hello!

I would like to create model's function which will shows most used categories. I have two tables - news and categories.

Table news: ID_article, title, content, date, ID_category, url
Table categories: ID_category, title, description, url

So this function must get number of using for each inserted category and this must be limited with 5.

Like this output:
Number of using | Name | Description
23 First First category
21 Second Second category
8 Third Third category

Thanks for help!


Sort results by number of using - El Forum - 03-09-2012

[eluser]InsiteFX[/eluser]
Code:
$this->db->order_by("column", "desc");



Sort results by number of using - El Forum - 03-09-2012

[eluser]aquary[/eluser]
You'll need a query to count number of news in each category, then sort it by the count... though this might be slow when your table got bigger...

Code:
// convert it to CI's AR yourself.
SELECT categories.*, COUNT(categories.ID_category) AS usage_time FROM categories JOIN news ON news.ID_category=categories.ID_category ORDER BY count(categories.ID_category) limit 5;

Not tested but something along that line. However, this is only limited to categories with at least 1 news inside. Empty categories will not be shown.


Sort results by number of using - El Forum - 03-14-2012

[eluser]someone Smile[/eluser]
Thanks for query, but I haven't ever working with SQL in this way. Could someone please help me to convert this to CI's AR?

Thanks! :-)


Sort results by number of using - El Forum - 03-23-2012

[eluser]someone Smile[/eluser]
Please help!

Thanks! :-)