问题
I have a sidebar with categories. when i click on one categorie it shows me the factories who are located in that category.
I did this using joins in codeigniter.
Now i want to show how much factories are in a category. so for example:
Categories.
Cars (2)
Books (7)
Animals (45)
So it simple has to show how much factories have that specific category.
i tried to do a simple count_all_results but then i get the total count of factories. but i want them to count by the specific id of categories.
my model function:
function categorieen_getall($segment3)
{
$this->db->where('categorieen.idcategorieen', $segment3);
$this->db->select('*');
$this->db->from('bedrijfcategorieen');
$this->db->join('categorieen', 'categorieen.idcategorieen = bedrijfcategorieen.idcategorieen');
$this->db->join('bedrijven', 'bedrijven.idbedrijven = bedrijfcategorieen.idbedrijven');
$query = $this->db->get();
$result = $query->result();
/*
echo '<pre>';
print_r($result);
*/
return $result;
}
My controller function:
function get_All()
{
$data['cat'] = $this->categorieen_model->categorieen_getall($segment3);
$this->load->view('views/sidebar', $data);
}
My view:
<div id="sidebar">
<?php
echo '<h3>Categorieën</h3>';
echo ($this->db->count_all_results('categorieen'));
?>
<hr>
<br/>
<?php
echo '<ul>';
if(isset($cat) && is_array($cat)){
foreach($links as $k => $value){
echo '<li>';
echo '<br>';
echo '<a href="'.base_url().'home/categorie/'.$value->idcategorieen.' ">' .$value->Categorie. '</a>';
echo '</li>';
}
}
echo '<ul>';
/*
if(isset($cat ) && is_array($cat )){
foreach($cat as $key => $row){
echo "Categorie:"; echo $row->Categorie;
echo "<br />";
echo $row->idcategorieen;
echo "<br />";
echo $row->Bedrijfsnaam;
}
}
*/
?>
</div>
My database scheme:
Factories
--------
idfactories
factoryname
adress
email
...
Categories
----------
idcategories
Category
Factorycategories
-----------------
idfactorycategories
idcategories
idfactories
回答1:
This is not quite suitable because I know there is a better way to do this, but this will do the work for you:
// Get categories
$categories = array();
$query = $this->db->query("select * from `Categories` order by `idcategories`");
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$query_count = $this->db->query("select `idfactorycategories` from `Factorycategories` where `idcategories` = {$row['idcategories']}");
$factory_count = $query_count->num_rows();
$categories[] = array(
'count' => $factory_count
);
}
}
For ease, you can first get categories in a foreach
loop and then for each of them submit a query for the factories
table to get relevant count of factories with that related category id.
回答2:
I asked another question. with the same problem and i solved it.
Look at my own answer with the solution i got!
Count results in joined table and show between () in sidebar
Thanks for the people who helped me :)
来源:https://stackoverflow.com/questions/15758599/show-number-of-factories-behind-categories-in-sidebar-codeigniter