Codeigniter正确的循环连接方式有多个结果?

时间:2011-05-24 16:25:01

标签: php mysql codeigniter

我将举一个小例子来解释我的意思。

CREATE TABLE blog
(
 b_id int primary key not null,
  b_title varchar(255) not null,
  b_body text not null,
  CONSTRAINT pk_b_id_01 PRIMARY KEY(b_id)
 )

 CREATE TABLE images
 (
  i_id int primary key not null,
  i_image varchar(255) not null,
  i_b_id int not null,
  CONSTRAINT pk_i_id_01 PRIMARY KEY(i_id)
 )

让我们说在一个管理区域我想要显示一个表格,其中包含博客的每个主题以及分配给它的所有图像,无论它有1个图像还是5个图像。

目前我这样做

$query = $this->db->get("blog");
foreach($query->result() as $qr)
{
    echo $qr->b_title . "<br />";
    $query2 = $this->db->get_where("images", array('i_b_id'=>$qr->b_id));
    foreach($query2->result() as $qr2)
    {
        echo $qr2->i_image . "<br />";
    }
    echo "<hr />\n";
}

我的问题是有一种方法可以通过1个查询而不是30个或多个帖子来完成此操作吗?

我尝试使用连接执行此操作但仅显示第一张图像。

$this->db->join("images", "i_b_id = b_id");
$query = $this->db->get("blog");
foreach($query->result() as $qr)
{
    echo $qr->b_title . "<br />";
    $query2 = $this->db->get_where("images", array('i_b_id'=>$qr->b_id));

    //is there another for loop i can do here?
    echo $qr->i_image . "<br />";

    echo "<hr />\n";
}

1 个答案:

答案 0 :(得分:0)

进行连接会导致每个图片的博客数据重复。为了避免反复出现相同的标题,只需使用一些简单的逻辑:

$current_blog_id = -1;
foreach($query->result() as $qr)
{
    // only output the title if it's a new blog
    if ($qr->b_id != $current_blog_id)
    {
        if ($current_blog_id != -1) echo "<hr />\n";

        echo $qr->b_title . "<br />";

        $current_blog_id = $qr->b_id;
    }

    echo $qr->i_image . "<br />";
}
相关问题