2013-03-04 127 views
2

嗨,大家好,我是新的codeigniter,目前正在項目中的一個小項目上工作,我試圖加入兩個表,並顯示在單個表中的數據。我看着那個笨有一個用戶指南我不知道這是如何工作codeigniter加入2表數據

$this->db->join();

什麼表應該是第一,什麼ID鍵應該是冷杉。有人可以更詳細地解釋我這個,請使用例子,如果你可以。我正在嘗試加入憑證表和tblanswers。 Tnx回答。

我試圖代碼中使用本實施例中的函數:

$this->db->select('*'); 
$this->db->from('blogs'); 
$this->db->join('comments', 'comments.id = blogs.id'); 

$query = $this->db->get(); 

編輯: ,而不是使用加入在笨方法是有可能使用一個簡單的函數來分別檢索兩個表中的數據?我想要的所有內容都是將數據庫表中的數據回顯到我的網站頁面中的html表中,以便顯示是否可以編寫兩個get函數來分別檢索兩個表?

+0

您可以在模型上創建兩個方法,並且每個方法都可以進行所需的查詢。 – 2013-03-04 11:52:45

回答

7

不要緊的位置是什麼表第一...簡單:

<?php 

$this->db->select('t1.name, t2.something, t3.another') 
    ->from('table1 as t1') 
    ->where('t1.id', $id) 
    ->join('table2 as t2', 't1.id = t2.id', 'LEFT') 
    ->join('table3 as t3', 't1.id = t3.id', 'LEFT') 
    ->get(); 
?> 
1
$this->db->join('comments', 'comments.id = blogs.id'); 

用這一行你告訴:在裏面搜索我的所有評論id等於blogs.id。

通常是這樣的,我認爲:

$this->db->join('comments', 'comments.blogs_id = blogs.id'); 

你必須插入到你的表名爲blogs_id場(unisgned int值),因爲博客可以有更多的評論。 不重要的第一或第二值

+0

所以如果兩個表數據具有相同的ID,連接將只能工作?例如tblanswers有身份證12和憑證有ID 12 – 2013-03-04 11:44:28

+0

在你的情況是,但我不知道你的數據庫如果是正確的 – 2013-03-04 11:47:36

+0

如果ids有相同的會有一個錯誤重複的ID? – 2013-03-04 11:53:35

0

嗨,這將在codeIgnator將兩個表工作。

$this->db->select("chat.id,chat.name,chat.email,chat.phone,chat.date,post.post"); 
     $this->db->from('chat'); 
     $this->db->join('post', 'chat.id = post.id'); 
     $query = $this->db->get(); 

    if($query->num_rows() != 0) 
    { 
     return $query->result(); 
    } 
    else 
    { 
     return false; 
    } 

您可以根據需要更改查詢,並使用跟蹤和錯誤方法來獲得適當的結果。