Codeigniter:查询循环两个结果

时间:2013-05-05 01:32:40

标签: php mysql 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()给出下一个和上一个图像而不是下一个和上一个图像集合。

1 个答案:

答案 0 :(得分: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>..

}

但是这最后一个代码意味着循环两次。

相关问题