2013-06-25 63 views
0

我有一個網站在codeigniter開發,我想要檢索特定T恤的評論。 我有一個表T恤那樣:檢索只有一行評論

- id 
- user_id 
- name 
- created 
- modified 

而且表tee_comments這樣的:

- id 
- user_id 
- tee_id 
- created 
- modified 

我做了這個查詢:

$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified'); 
    $this->db->from('tee'); 
    $this->db->join('tee_comments', 'tee_comments.tee_id = tee.id','left outer'); 
    $this->db->order_by("tee.created", "desc"); 
    $query = $this->db->get(); 

與此查詢我取回兩行因爲我在發球臺有兩條評論。

我的目標是獲取只有一排,其中裏面有像註釋的數組:我曾嘗試到

tee{ 
    id, 
    name, 
    created, 
    modified 
    comment{ 
    [0] 
     id, 
     tee_id, 
     comment, 
     created, 
     modified 
    [1] 
     id, 
     tee_id, 
     comment, 
     created, 
     modified 
    } 
} 

聯接: - 左 - 右 - 左外 - 右外

但沒有解決問題,有沒有辦法做到這一點? 謝謝

+0

數據庫查詢從(組合)表中檢索行。如果你想要一個嵌套的結構,你必須在php中自己生成。 – jeroen

+0

您必須手動將評論數據與相應的T恤記錄相結合 – landons

+0

您的問題表明您只需要1行評論,但是您想要實現的內容包含多個評論? – bottleboot

回答

1

我喜歡CodeIgniter!我經常使用它!這裏有兩個非常簡單的選項:

一種方法是使用limit

$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified'); 
$this->db->join('tee_comments', 'tee_comments.tee_id = tee.id','left outer'); 
$this->db->order_by("tee.created", "desc"); 
$query = $this->db->limit(1)->get('tee'); 

另一種方式是獲得第一項results Array

$query = $this->db->get(); 
$results = $query->result(); // gets return as an array 
$row = $results[0]; // will be first row in results array 

記住壽,$row將返回作爲object(stdClass)意味着你必須從中檢索之類的東西$row->column_name

一個方便的小片段,我喜歡在下面的電話後使用。它代替行ObjectArray

$results = $db->get('tee')->result(); // snippet comes after you have result array 
// snippet here 
foreach ($r as $k => $v) { $results[$k] = array(); foreach ($v as $kk => $vv) { $results[$k][$kk] = $vv != "NULL" ? trim($vv) : ""; } } 
0

使用$this->db->limit(1)檢索單個記錄。

據對this question接受的答案,你可能需要之前選擇把極限聲明:

$this->db->limit(1); 
$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified'); 
$this->db->from('tee'); 
+0

但我必須檢索所有發球與他們的評論,例如我知道限制可以檢索只有一個記錄,但不是這種情況 –

+0

嗯,在這種情況下,它可能是不可能的。在這裏看到答案:http://stackoverflow.com/questions/6105451/limit-sql-join-when-using-codeigniter-active-record-class –

0

選項之一:

for ($i = 0; $i < count($records); $i++) 
{ 
$data = $records[$i]; 
// work with date. 
if($i == 1) 
    break; 
} 

選項二: 剛分配的第一行變種

$row = $records['tee']['comment'][0];