【问题标题】:codeigniter , mysql代码点火器
【发布时间】:2012-09-28 06:46:42
【问题描述】:

我是 CI 新手,我遇到了 MySQL 问题

表 1

id | house_id | 
1  |  1       | 
2  |  4       | 
3  |  3       | 

表2

house_id | image_name | 
4        |  a.jpg     | 
4        |  b.jpg     | 
3        |  c.jpg     | 

如何使用 CodeIgniter Active Record 类为每个 house_id 选择(独特的)image_name

【问题讨论】:

  • Hehe Kemal,你打败了我。 @datta,请不要用 HTML 标记您的问题。 StackOverflow 使用 Markdown。使用提供的工具栏标记您的问题。谢谢。

标签: php mysql codeigniter activerecord


【解决方案1】:

http://codeigniter.com/user_guide/database/active_record.html 这是您正在寻找的 API $this->db->distinct();

【讨论】:

    【解决方案2】:

    只需在 codeigniter 模型中使用一个简单的方法 group_by

    function get_house_image(){
    $items = $this->db->select('house_id', 'image_name')
    ->from("table1")
    ->join("table2", "table1.house_id = table2.house_id")
    ->group_by("table1.house_id")  
    ->get();    
    return $items->result_array();
    }
    

    【讨论】:

      【解决方案3】:

      在你的模型中

      function get_house_image($id){
      $this->db->where('house_id',$id);
      $query = $this->db->get('table2');
      return $query->result();
      }
      
      In your cotroller
      function house($id){
      $data['house'] = $this->your_model->get_house_image($id);
      $this->load->view('your_view',$data);
      

      在您看来 foreach 结果并使用它。这将获取您在 url 中传递的 id 的房子的图片。

      【讨论】:

        【解决方案4】:

        您可以使用表的左连接来获取记录,如下所示:

        $this->read->select('t1.house_id,t2.image_name');
         $this->read->join('table2 as t2','t1.house_id = t2.house_id','left');
         $result = $this->read->get('table1 as t1');
        if($result){
              $data = $result->result_array();
              print_r($data);
        }
        

        【讨论】:

          猜你喜欢
          • 2012-02-09
          • 2011-06-04
          • 2016-01-28
          • 2012-06-30
          • 2012-02-21
          • 2011-03-29
          • 2011-08-06
          • 1970-01-01
          • 2011-07-28
          相关资源
          最近更新 更多