Reputation: 301
I have two tables.
Table 1: table_company
+---------------------------+
| company_id | company_name |
+---------------------------+
| 1 | Apple |
| 2 | Samsung |
+---------------------------+
Table 2: table_products
+------------+--------------+-------------+-----------+
| product_id | product_name | category_id |company_id |
+-----------------------------------------------------+
| 1 | iPhone | 3 | 1 |
| 2 | galaxy | 3 | 2 |
| 1 | iPad | 4 | 1 |
| 2 | tab | 4 | 2 |
+-----------------------------------------------------+
I want to join this 2 tables to get the company name according to category_id.
I wrote the following code in my model. but did not get anything. Please help.
public function select_company_by_category_id($category_id) {
$this->db->select('*');
$this->db->from('tbl_products');
$this->db->join('tbl_company', 'company_id = company_id');
$this->db->where('category_id', $category_id);
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}
Upvotes: 1
Views: 58
Reputation: 16117
First of all open your database error from database.php file only on development line not on production.
Than issue is that company_id
is available in both tables with same name than you must need to add table alias as:
public function select_company_by_category_id($category_id)
{
$this->db->select();
$this->db->from('table_products');
$this->db->join('table_company', 'table_company.company_id = table_products.company_id');
$this->db->where('table_products.category_id', $category_id);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
Upvotes: 0
Reputation: 38672
Use Left Join for this
public function select_company_by_category_id($category_id) {
$this->db->select('*');
$this->db->from('table_products');
$this->db->join('table_company', 'table_company.company_id = table_products.company_id', 'left'); # Changed
$this->db->where('table_products.category_id', $category_id); # Changed
$query = $this->db->get(); # Improved
$result = $query->result_array(); # Improved
return $result;
}
Upvotes: 1
Reputation: 165
try to replace your join with this:
$this->db->join('tbl_company', 'tbl_company.company_id = tbl_products.company_id');
you can find more examples in codeigniter active record page
Upvotes: 1