【问题标题】:Codeigniter 2.1 - MySQL JOINCodeigniter 2.1 - MySQL JOIN
【发布时间】:2013-05-21 11:28:21
【问题描述】:

我有两张桌子:

MENU
->id_menu
->title
->page_id
->order

PAGES
->id_page
->title
->page
->slug

这是选择功能:

public function get_all_menu()
    {
        return $this->db
        ->select('menu.*, pages.id_page, pages.title AS page_title')
        ->from($this->table)
        ->join('pages','id_page = page_id')
        ->order_by($this->order_by)
        ->get()
        ->result_array();
    }

这是我的问题 - 菜单中的项目可以与页面连接,但也可以单独(不连接到页面)。这意味着 MENU 表中的 page_id 可以为 0。如果 page_id 为 0,则我无法从上述查询中获取该行。如何获取菜单中的所有项目(与页面连接的和与页面无关的)?

【问题讨论】:

  • LEFT OUTER JOIN使用自定义查询
  • @STTLCU 它正在工作:)。如果你能写出答案,我可以给你点赞:)。
  • 完成,@Sasha。有比我更好的答案。

标签: php mysql codeigniter codeigniter-2


【解决方案1】:

您需要在->join() 中添加join type

喜欢

public function get_all_menu()
 {
    return $this->db
    ->select('menu.*, pages.id_page, pages.title AS page_title')
    ->from($this->table)
    ->join('pages','id_page = page_id','left')
    ->order_by($this->order_by)
    ->get()
    ->result_array();
}

参见参考手册Active Record

【讨论】:

    【解决方案2】:

    根据 cmets 的要求:

    您需要使用“LEFT JOIN”从表中检索部分或不完整的值。

    在这种情况下,常规连接正在查找两个表之间的匹配项。由于其中一个表中没有 id 0,因此无法检索到匹配项并且不会选择该行。

    如果未检索到匹配项,则使用 LEFT JOIN(或适当时使用 RIGHT JOIN,基于“不完整”表),结果还将包含未匹配的行,其中所有 NULL另一个表的值

    【讨论】:

    • 感谢您帮助我并解释问题:)
    【解决方案3】:

    从你的控制器调用模型中的这个方法说你的模型名称是 general_model

    $value=('menu.*, pages.id_page, pages.title AS page_title');
            $joins = array
            (
                  array
                    (
                      'table' => 'pages',
                      'condition' => 'menu.id_page = pages.page_id',
                      'jointype' => 'leftouter'
                     ),
    
            );
    $where_condition=array('menu.Id '=>'Enable','restaurant.Id'=>$rest_id);
                $data['detail'] = $this->general_model->get_joins('menu',$value,$joins,$where_condition,'menu.Id','asc')->result();
    

    这里的 $where_condition 是你想要传递的 where 条件,如果你想删除你可以从函数中删除它。最后两个参数是 orderby

    只需在您的连接模型中使用此功能

    public function get_joins($table,$value,$joins,$where,$order_by,$order)
        {
            $this->db->select($value);
             if (is_array($joins) && count($joins) > 0)
              {
                 foreach($joins as $k => $v)
                   {
                    $this->db->join($v['table'], $v['condition'], $v['jointype']);
                   }
              }
             $this->db->order_by($order_by,$order);
             $this->db->where($where);
            return $this->db->get($table);
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-04
      • 2017-09-27
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      相关资源
      最近更新 更多