2014-07-02 133 views
0

我有announcements表,其中我存儲了announcements.catid(類別ID)。MySQL在CodeIgniter中在同一個表中加入兩個不同的列兩次

分類表categories用於嵌套使用categories.pid

我想要做的是獲取在多維數組內嵌套的類別。

這裏是我怎麼想它是在圖像內突出部分:

enter image description here

這裏是代碼:

public function get_mixed($limit = NULL, $offset = NULL) 
{ 
    $this->db 
     ->select(' 
      announcements.id, 
      announcements.catid, 
      announcements.uid, 
      categories.title AS section, 
      categories.title AS category, 
      announcements.title, 
      announcements.text, 
      announcements.views, 
      announcements.created, 
      announcements.modified, 
      announcements.pubdate 
     ') 
     ->join('categories', 'announcements.catid = categories.id', 'left') 
     ->join('categories as section', 'categories.pid = section.id', 'left') 
     ->order_by('created DESC, '.$this->_order_by); 

    return $this->db->get($this->_table_name, $limit, $offset)->result(); 
} 

我第一次嘗試通過創建section別名,但它得到了同樣的結果。

也許有更好的方法?

回答

1

如果您走樣categories的一個任命爲section,那麼你就需要引用你想要的任何領域,從categories表作爲section.[field](例如,section.title

不知道你想要什麼,我最好的猜測在你的修改後的查詢將是:

$this->db 
    ->select(' 
     announcements.id, 
     announcements.catid, 
     announcements.uid, 
     section.title AS section, 
     categories.title AS category, 
     announcements.title, 
     announcements.text, 
     announcements.views, 
     announcements.created, 
     announcements.modified, 
     announcements.pubdate 
    ') 
    ->join('categories', 'announcements.catid = categories.id', 'left') 
    ->join('categories as section', 'categories.pid = section.id', 'left') 
    ->order_by('created DESC, '.$this->_order_by); 
+0

正是我想要的,我忘了在SELECT中引用別名。謝謝 – aspirinemaga

相關問題