简体   繁体   中英

In Codeigniter, get the count of rows that including an ID number which is primary key in another table

I have two tables, first ones name is organizations like this:

ID | org_name
1 - Congress1
2 - Congress2
3 - Congress3
4 - Congress4

And the other table is visitors like this:
ID | visitors | organizationID
1 - W. Rooney - 1
2 - S. Aguero - 1
3 - C. Ronaldo - 2
4 - L. Messi - 4

My problem is:For every organizations ID, how can I count the rows that including organizationsID in visitors table like that:

organizationsID=1 > row count in visitors=2
organizationsID=2 > row count in visitors=1
organizationsID=3 > row count in visitors=0
organizationsID=4 > row count in visitors=1
And that problem is in Codeigniter framework. My model function:

$dbase->select('*');
$dbase->from('organizations');
$dbase->order_by("org_startdate", "desc"); 
$query = $dbase->get(); 

My controller function:

$this->load->model('organizations_m');
$data['organizations'] = $this->organizations_m->organizations();
$this->load->view('organizations_v', $data);

And finally in my view i list my organizations:

foreach ($organizations as $org){
echo "Organization Name:".$org->org_name;
echo "Count of visitors that joining to this Organization".MY PROBLEM IS HERE;
}

My final result should be shown in the browser like that:
Organization Name: Congress1
Count of visi... : 2

Organization Name: Congress2
Count of visi... : 1

Organization Name: Congress3
Count of visi... : 0

Organization Name: Congress4
Count of visi... : 1

Thank you for your replies..

In your model:

$dbase->select('o.org_name,COUNT(v.id) AS no_visitors', FALSE);
$dbase->from('organizations o');
$dbase->join('visitors v', 'o.id = v.organizationID', 'left');
$dbase->group_by('o.id');
$dbase->order_by("org_startdate", "desc"); 
$query = $dbase->get();

Then in your view

foreach ($organizations as $org){
echo "Organization Name:".$org->org_name;
echo "Count of visitors that joining to this Organization".$org->no_visitors;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM