Welcome Guest, Not a member yet? Register   Sign In
Fetch data from many tables
#1

[eluser]Lykos22[/eluser]
Hi I'd like some help please, I 've been struggling for some days but I can figure out a proper solution.

I have created these 3 db tables and each table is also associated with a model, so table products has product_model, features has feature_model etc etc.
Code:
Table: products
product_id // e.g. 1, 2, 3, ...
product_name // e.g. Apple Imac, Nikon DSLR, ...
category_id // e.g. 4, 5, ...   (these are sub-categories like, Desktops, Cameras etc etc)
description
etc etc

Table: features
feature_id // e.g. 1, 2, 3, ...
feature_name // e.g. RAM, Zoom, Processor
category_id // e.g. 1, 2 ... (these are the parent categories)

Table: product_features, note that currently is empty
id
product_id  // e.g. 1, 2, 1, ...
feature_id  // e.g. 1, 2, 3, ...
feature_value  // e.g. 512Mb, 12Mpx, Intel I5, etc etc ...

I have created a form in my view, in which I want to display all features (depend on the the parent category) that a product may have and assign to them some values either when adding new or editing the existing ones, for instance:
- for the Apple Imac product, I want to fetch all features that belong to (parent)category_id = 1 (Computers), and assign some values to them for this specific product and store them in the database.

I also use a MY_Model in my application and the function I have created so far for fetching the data from the database is this
Code:
// in my feature_model
public function get_features_values($product_id, $parent_category_id){
  $this->db->select('features.*, product_features.feature_value')
  ->join('product_features', 'features.feature_id=product_features.feature_id', 'left')
  ->join('products', 'products.product_id=product_features.product_id', 'left');
  return parent::get_by(array('features.category_id'=>$parent_category_id, 'product_features.product_id'=>$product_id));
}

// Which produces this query:
SELECT `features`.*, `product_features`.`feature_value`
FROM (`features`)
LEFT JOIN `product_features` ON `features`.`feature_id`=`product_features`.`feature_id`
LEFT JOIN `products` ON `products`.`product_id`=`product_features`.`product_id` // *
WHERE `features`.`category_id` =  '1'
AND `product_features`.`product_id` =  '1' // *

The problem I face is that I get nothing returned from the database, whereas if I remove the lines where the * is in the query, then the query returns
feature_id // 1,2, etc etc as expected
feature_name // RAM, Processor, etc etc as expected
category_id // the parent category_id eg Computers as expected
feature_value // all null as expected cause product_features is curerntly empty, but if a product has values for some specific features then should fetch the values that match with the product.

How can I accomplish this? Any help would be appreciated.




Theme © iAndrew 2016 - Forum software by © MyBB