CodeIgniter中的一对多数据库关系

时间:2012-11-20 09:57:32

标签: database codeigniter relationship

我有一些产品和一些图像。有更多的图像,他们有一个p_id。我如何获得多个?这是一个画廊。 我目前的查询:

    $this->db->select('prod_id, prod_name, prod_link, prod_description, prod_status, prod_price, brand_link, link, cat_link, normal, thumbnail');

    $this->db->from('product');
    $this->db->join('category', 'cat_id = prod_category');
    $this->db->join('brands', 'brand_id = prod_brand');
    $this->db->join('images', 'p_id = prod_id');

    $query = $this->db->get();

    return $query->row_array();

这只会给我第一张图片以及其他信息。如果我将它更改为result_array(),它也会给我第二个,但在另一个数组中。 (以及产品的其他结果,这没有意义)。

1 个答案:

答案 0 :(得分:4)

如上所述,您可以再次访问数据库以获取该产品的图像数组,然后将这些结果添加回原始查询数组中。

$this->db->select('prod_id, prod_name, prod_link, prod_description, prod_status, prod_price, brand_link, link, cat_link, normal');
$this->db->join('category', 'cat_id = prod_category');
$this->db->join('brands', 'brand_id = prod_brand');
$query = $this->db->get('product')->result_array();

// Loop through the products array
foreach($query as $i=>$product) {

   // Get an array of products images
   // Assuming 'p_id' is the foreign_key in the images table
   $this->db->where('p_id', $product['prod_id']);
   $images_query = $this->db->get('images')->result_array();

   // Add the images array to the array entry for this product
   $query[$i]['images'] = images_query;

}
return $query;