2014-07-02 135 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

相关问题