user1454771
user1454771

Reputation: 107

One-to-many DB relationship in CodeIgniter

I have some products and some images. There are more images and they have a p_id. How do I get more than one? It's for a gallery. My current query:

    $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();

This only gives me the first image along with the rest of the information. If I change it to result_array() it gives me the second one as well but in another array. (along with other results from products, which doesn't make sense).

Upvotes: 3

Views: 12352

Answers (1)

Jeemusu
Jeemusu

Reputation: 10533

As I mentioned above, you could hit the database a second time to get the images array for that product, and then add those results back into the original query array.

$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;

Upvotes: 6

Related Questions