1
我會舉一個小例子來解釋我的意思。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";
}