0

我需要帮助为 codeigniter 编写数据库模型。我有 2 张桌子。首先,我保存了所有产品,在第二个表中,我有产品 ID 和类别 ID。因此,例如:

餐桌用品

t-shirt with ID 1
polo shirt with ID 2

类别

shirts with ID 5

产品_cat

product_id category_id
---------- ------------
1 5
2 5

我如何编写模型来获取所有产品及其信息,使用表格protucts_cat并获取它->result()

4

2 回答 2

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;
于 2012-08-28T04:46:52.703 回答
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();
于 2012-08-27T23:27:09.037 回答