在CodeIgniter查询中连接多个表

时间:2013-02-08 12:55:42

标签: mysql codeigniter

我想在CodeIgniter中运行查询。

查询

"SELECT * FROM td_album,td_image
     WHERE td_album.album_id=td_image.album_id
          AND td_album.album_id='$id'
          AND (td_image.image_name='$name' OR td_image.image_id='$image_id');"

当我在CodeIgniter查询中运行时,我写为:

$query = $this->db->select('*')
                        ->from('td_image')
                        ->join('td_album', 'td_album.album_id = td_image.album_id')
                        ->like('td_image.image_id', $image_id)
                        ->or_like('td_image.image_name', $image_name)
                        ->and_like('td_album.album_id',$id)
                        ->get('', $this->limit, $this->offset);

但我不知道为什么这不成功。

修改

它抛出了这个错误:

  

致命错误:在第189行的/home/koushani/public_html/jmssimplex.com/application/admin/models/gallery_model.php中调用未定义的方法CI_DB_mysql_driver :: and_like()

2 个答案:

答案 0 :(得分:3)

因为and_like不是活动记录函数。所以你可以在查询中使用多个

试试这个

$query = $this->db->select('*')
                        ->from('td_image')
                        ->join('td_album', 'td_album.album_id = td_image.album_id')
                        ->like('td_image.image_id', $image_id)
                        ->or_like('td_image.image_name', $image_name)
                        ->like('td_album.album_id',$id)
                        ->get('', $this->limit, $this->offset);

另一种方式是

$array = array('td_image.image_id' => $image_id, 'td_album.album_id' => $id);
$this->db->select('*');
$this->db->from('td_image');
$this->db->join('td_album', 'td_album.album_id = td_image.album_id');
$this->db->like($array);
$this->db->or_like('td_image.image_name', $image_name);
$this->db->limit($this->limit, $this->offset);
$query = $this->db->get();

答案 1 :(得分:0)

你应该写如下

$this->db->select('*')
                ->from('td_image,td_album')
                ->where('td_album.album_id', 'td_image.album_id')
                ->where('td_album.album_id', $id)
                ->where('td_image.image_name='.$name.' OR td_image.image_id='.$image_id);
$query = $this->db->get();