2013-05-05 145 views
0

我試圖通過兩個連接的數據表循環。一張桌子是一個圖像集合,另一個是圖像。圖像有一個外鍵來收集。Codeigniter:循環查詢兩個結果

我的問題是,我如何在我看來實現以下目標?

foreach ($collections as $collection) { 

    echo '<ul>'; 

    foreach ($collection->image as $image) { 
     echo '<li><img src="'.$image->url.'" /></li>'; 
    } 

    echo '</ul>'; 

} 

我目前的控制器使用此:

class Collection extends CI_Controller { 

    public function index() 
    { 
     $this->load->model('Collection_model'); 

     $data['collections'] = $this->Collection_model->get_latest_collections(); 

     $this->load->view('collection_view.php', $data);  

    } 
} 

,並具有以下型號:

class Collection_model extends CI_Model { 

    function get_latest_collections() 
    { 
     $this->db->select('*'); 
     $this->db->from('photo'); 
     $this->db->join('collection', 'photo.collection_id = collection.id'); 
     $this->db->order_by("collection.date_created", "DESC"); 

     $query = $this->db->get(); 

     return $query->result(); 
    } 

} 

與上面的問題是,當我通過收集結果循環我實際上是直接通過所有圖像循環。我不得不在視圖中添加一些邏輯來檢查集合ID是否已更改爲放入。這意味着我不能使用next()和prev()來獲取下一個和上一個集合,因爲循環在圖像中循環,next()和prev()會給出下一個和上一個圖像,而不是下一個和上一個採集。

回答

0

如果我很好地理解你的問題,你想循環你的照片,並按收藏組織他們。

有幾種方法可以實現這一點,但這不能通過連接查詢,因爲表關係是一個(集合)對許多(照片)。

解決方案1:您想顯示你所有的照片

//get all collections 
$collections = $this->db 
    ->order_by("date_created", "DESC") 
    ->get('collection') 
    ->result(); 

//get all photos 
$photos = $this->db 
    ->get('photo') 
    ->result(); 

解決方案2:你想表現出一定的收藏

//get some collections 
$collections = $this->db 
    //->where('..', '..') //some filtering 
    ->order_by("date_created", "DESC") 
    ->get('collection') 
    ->result(); 

//extract ids 
$collection_ids = array(); 

foreach($collections as $collection) 
{ 
    $collection_ids[] = $collection->id; 
} 

//get photos who are in these collections 
$photos = $this->db 
    ->where_in('collection_id', $collection_ids) 
    ->get('photo') 
    ->result(); 

在你看來

兩個上面的解決方案與此一起工作頌。

//loop on collections 
foreach($collections as $collection) 
{ 
    //<ul>.. 
    foreach($photos as $photo) 
    { 
     if($photo->collection_id == $collection->id) 
     { 
      //<li>..$photo->url.. 
     } 
    } 
    //</ul>.. 
} 

或讓你在你的代碼

//loop on collections 
foreach($collections as $collection) 
{ 
    $collection->images = array(); 

    foreach($photos as $photo) 
    { 
     if($photo->collection_id == $collection->id) 
     { 
      $collection->images[] = $photo; 
     } 
    } 
} 

//so in your view (what you expected) 
foreach($collections as $collection) 
{ 
    //<ul>.. 

    foreach($collections->images as $image) 
    { 
     //<li>..$image->url.. 
    } 

    //</ul>.. 

} 

第一塊預期正是但這最後的代碼意味着循環兩次。