2016-04-26 7 views
0

私は2つのテーブルを持っています、最初のものは次のような組織です:
ID | org_name
1 - Congress1
2 - Congress2
3 - Congress3
4 - Congress4

もう1つのテーブルは次のような訪問者です:
ID |ビジター| organizationID
1 - W.ルーニー - 1
2 - S.アグエロ - 1
3 - C.ロナウド - 2
4 - L.メッシ - 4Codeigniterで、別のテーブルの主キーであるID番号を含む行の数を取得します

私の問題は、次のとおりです。すべての組織の場合はID、私は数えることができますか

organizationsID = 1>訪問者の行数= 2
organizationsID = 2>訪問者の行数= 1
organizationsID = 3>訪問者の行数= 0
organizationsID =:そのような訪問者テーブルにorganizationsID含む行4>訪問者の行数= 1
この問題はCodeigniterフレームワークにあります。 私のモデル関数:

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

私のコントローラ機能:

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

そして最後に私の見解で、私は自分の組織をリスト:

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

が私の最終的な結果は以下のようにブラウザに表示されなければならないがその:
組織名:Congress1
ビジター数:2

組織名:VISIのCongress2
カウント...:1

組織名:VISIのCongress3
カウント...:0

組織名:VISIのCongress4
カウント.. 。:

1はあなたの応答をありがとう...あなたのモデルでは

+0

この質問http://stackoverflow.com/questions/7424913/how-to-count-the-number-of-instances-of-each-を見てみましょうテーブル内の外部キーID – Artamiel

答えて

0

$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(); 

その後、あなたのビューで

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