i have this problem in codeigniter:
I try to make a navigation tree system from database.
model:
function getServices()
{
$this->db->select('service_url, service_title, category_title');
$this->db->join('services_category', 'services_category.id=services.category_id');
$this->db->group_by('category_title');
$this->db->order_by('service_title', 'ASC');
$query = $this->db->get('services');
if($query->result() == TRUE)
{
foreach($query->result_array() as $row)
{
$result[] = $row;
}
return $result;
}
}
view:
<?php if(isset($services) && $services) : foreach($services as $s) : ?>
<ul>
<li><a href="#"><?php echo $s['category_title'] ?></a>
<ul>
<li><?php echo anchor('services/' . $s['service_url'], $s['service_title']); ?></li>
</ul>
</li>
</ul>
<?php endforeach; ?>
<?php endif; ?>
now so far so good, the result is returning each category the way is supposed to, but the service is returning only one service per category, and in some categories there is like 15 services.
Anybody kind to give me a hand, or an explanation what is going wrong ?
Thank you so much.
“i’m not an expert in php or codeigniter, i just started not long time ago, so please don’t shoot the beginner.”
note: i tried without the group_by and order_by, and is returning all services, but the categories are repeating,
ex:
category-a
service1
category-a
service2
category-b
service10
category-b
service11
category-c
service30
category-c
service31
....
This is a good read for aggregate functions when using Group By (MySQL).
A simple explanation would be like this
Now using SUM aggregate function like this.
The result will be:
In your scenario,
GROUP BYwill not work as intended as it will only get one Category since you grouped your query by each category.The ideal solution to this is to have 2 separate functions,
GetCategoriesandGetServices.Then in your view file, you just need to do a for loop on the Categories then do another query for each Category. Here’s an outline of what it will look like,