我需要帮助编写codeigniter的数据库模型。我有2张桌子。首先,我已经保存了所有产品,在第二个表中,我有类别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()
获取?
答案 0 :(得分: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();
答案 1 :(得分: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;