Codeigniter:无法使用join获取字段值

时间:2013-03-31 14:16:53

标签: php mysql codeigniter join

我有第三个表的外键ID,例如(thirdsubmenu_idthirdsubmenu。我想从父表menu_name中获取mainmenu名称。 请参阅下面的数据库表结构以获取完整的详细信息

数据库结构

 1)Table: mainmenu
    ---------------
     mainmenu_id   PK(primary key)
     menu_name     ..... 

    2)Table: submenu
    -------------------
     submenu_id     PK
     mainmenu_id    FK (foreign key refrences mainmenu table)
     submenu_name   ..... 


    3)Table: thirdsubmenu
    --------------------
      thirdsubmenu_id     PK
      submenu_id          FK (foreign key refrences submenu table)
      thirdsubmenu_name     ........

我尝试使用以下代码从menu_name表中获取mainmenu但我收到了错误。

 //---------------------------get Main Menu Name by thirdsubmenu_id-----------------------------------
function getMainMenuNameOfSubmenu($thirdsubmenu_id)
{
    $this->load->database();   
    $this->db->select('*');
    $query=$this->db->join('mainmenu', 'mainmenu.mainmenu_id = submenu.mainmenu_id', 'left')
           ->join('submenu', 'submenu.submenu_id = thirdsubmenu.submenu_id', 'left')
           ->get_where('thirdsubmenu',array('thirdsubmenu_id'=>$thirdsubmenu_id));  

    return $query->row('menu_name');   
}

我得到的错误是:

    A Database Error Occurred

    Error Number: 1054

    Unknown column 'submenu.mainmenu_id' in 'on clause'

    SELECT * FROM (`thirdsubmenu`) LEFT JOIN `mainmenu` ON `mainmenu`.`mainmenu_id` = `submenu`.`mainmenu_id` LEFT JOIN `submenu` ON `submenu`.`submenu_id` = `thirdsubmenu`.`submenu_id` WHERE `thirdsubmenu_id` = '17'

    Filename: D:\xampp\htdocs\system\database\DB_driver.php

    Line Number: 330

1 个答案:

答案 0 :(得分:0)

您创建父子关系的方法不正确。 考虑有10个,20个或50个子菜单。你会怎么做?为每一个创建一个表?

您可以将所有关系保存在一个表中,只需添加一个引用每个菜单父级的列。然后使用递归函数,您可以获得菜单的所有树。

现在关于您的问题,问题是您要thirdsubmenu加入mainmenu,然后引用submenu`.`mainmenu_id这是submenu的一列 这就是你看错的原因。

试试这段代码:

function getMainMenuNameOfSubmenu($thirdsubmenu_id)
{
    $this->load->database();   
    $this->db->select('*');
    $this->db->from('mainmenu');
    $this->db->join('submenu', 'mainmenu.mainmenu_id = submenu.mainmenu_id', 'left')
           ->join('thirdsubmenu', 'submenu.submenu_id = thirdsubmenu.submenu_id', 'left')
           ->where('thirdsubmenu.thirdsubmenu_id = "' . $thirdsubmenu_id . '"'); 
    $query = $this->db->get();
    return $query->row('menu_name');   
}