2012-08-27 104 views
0

我需要幫助編寫codeigniter的數據庫模型。我有兩張桌子。首先,我保存了所有產品,並在第二個表格中填寫了產品的ID和ID。因此,舉例來說:模型結構

產品

t-shirt with ID 1 
polo shirt with ID 2 

類別

shirts with ID 5 

protucts_cat

protuct_id category_id 
---------- ----------- 
1  5 
2  5

如何使用表格protucts_cat獲取所有產品及其信息,並通過->result()獲取?

回答

1

我傾向於寫複雜的查詢,而AR,但你可以用AR做到這一點:

return $this->db->query(' 
    SELECT 
     products.id AS product_id, 
     products.name AS product_name, 
     categories.id AS category_id, 
     categories.name AS category_name 
    FROM 
     products_cat 

    LEFT JOIN 
      products 
     ON 
      products.id = products_cat.product_id 

    LEFT JOIN 
      categories 
     ON 
      categories.id = products_cat.category_id 

    WHERE categories.id = '.$category_id.' 
')->result(); 
+0

對不起,我忘了寫我只想從一個類別中選擇產品,例如:http://example.com/category/5/我想只選擇表中具有id爲5的category_id的產品protucts_cat – Geril

+0

@Ger il加上我的回答的地方聲明 –

+0

是的,它的工作原理謝謝:) – Geril

1

假設每一件產品都映射到一個類別我會做使用活動記錄一個簡單連接:

$this->db->select('product.id as product_id, product.name as name, categories.name') 
$this->db->from('product p'); 
$this->db->join('protucts_cat pc','pc.product_id = p.id'); 
$this->db->join('categories c','c.id = pc.id'); 
$query = $this->db->get(); 

if($query->num_rows){ 
return $query->result(); 
} 
return false; 
+0

這樣做的工作? @Geril –

+1

雅,工作很好,非常感謝:) – Geril