2012-11-24 42 views
0

新的CodeIgniter和MVC/OOP工作爲好。我目前正在努力解決的問題涉及2個表格。CodeIgniter2 - 2個表關係


庫表

ID

的ClientID


客戶表

ID

名稱


畫廊[ 'clientID的']引用客戶端[ '身份證'],所以我可以檢索名稱。目前我gallery_model.php文件看起來像

class Gallery_model extends CI_Model 
    { 

     public function __construct() 
     { 
      $this->load->database(); 
     } 

    //Get all in progress galleries from client 
    public function get_progress($id = FALSE , $clientRef = '205') 
    { 
     if($id == FALSE) { 
      $query = $this->db->get_where('gallery', array('clientRef' => $clientRef, 'finish' => '0')); 
      return $query->result_array(); 
     } 
    } 
    //Get all proofed galleries from client 
    public function get_proofed($id = FALSE , $clientRef = '205') 
    { 
     //get all galleries from client 
     if ($id == FALSE) { 
      $query = $this->db->get_where('gallery',array('clientRef' => $clientRef, 'finish' => '1')); 
      return $query->result_array(); 
     } 
    } 

    //get the gallery selected 
    public function get_gallery($id , $clientRef = '205') 
    { 
     //This returns individual galleries 
     $query = $this->db->get_where('gallery', array('id' => $id)); 
     return $query->row_array(); 
    } 
} 

我的控制器看起來像:

public function index() 
    { 
     //Proofed Albums 
     $data['gallery'] = $this->gallery_model->get_proofed(); 
     //Albums that are in progress 
     $data['in_progress'] = $this->gallery_model->get_progress(); 

     $this->load->view('templates/header',$data); 
     $this->load->view('gallery/index',$data); 
     $this->load->view('templates/footer'); 
    } 

然後視圖的出看跌期權

$gallery['name'] - $gallery['clientId'] 

什麼是有點像最佳實踐這個。我知道這可能是簡單的,但我要開始了正確的事情了。我應該使用$this->db->join();

提前感謝這個幫助。

回答

1

使用$this->db->join()確實是最好的(也是通過Active Records完成的唯一方法,無需添加您自己的SQL),可以在一個查詢中從多個表中獲取信息。

您可能已經意識到這一點,但爲了以防萬一(爲了未來訪問此頁面的人),CodeIgniter User Guide有一個很好的頁面,詳細說明如何使用活動記錄。

內的默認加入應罰款爲您的目的。如果您有沒有客戶鏈接到他們的圖庫條目,並且希望他們包含在結果中,那麼您可能需要考慮其他類型的連接,您可以使用read about here

+0

感謝您的文檔建議! – Bungdaddy

+1

@Bungdaddy [NetTuts]上還有一系列漂亮的視頻(http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-day-1/)。他們現在變得有點老了,但他們是偉大的基礎,如果你喜歡從視頻中學習。 NETTUTS也有多種[其他笨論文](http://net.tutsplus.com/tag/codeigniter/),你可能會發現信息。看完前幾部影片後,我會隨時使用CodeIgniter用戶指南,但NetTuts文章可能對更具體的場景有用。 –

2

William's answer跟進,你可以做一個加入使用CI的Active Record的

$this->db->from('gallery')->join('client', 'gallery.id = client.id')->get()