phpcodeigniterjoinactiverecordwhere-clause

How to write CodeIgniter active record where() comparing two columns


I have these two tables:

+-------------+--------------+
| products_id | product_name |
+-------------+--------------+
|           1 | Pizza x      |
|           2 | Pizza Y      |
|           3 | Pizza A      |
|           4 | Pizza Z      |
|           5 | Pizza W      |
+-------------+--------------+

+----+-------------+----------+----------+
| id | products_id | order_id | quantity |
+----+-------------+----------+----------+
|  1 |           1 |        5 |        3 |
|  1 |           2 |        5 |        4 |
|  2 |           3 |        6 |        3 |
|  2 |           4 |        6 |        3 |
|  3 |           5 |        7 |        2 |
+----+-------------+----------+----------+

I want to select products_name and quantity for every order_id. I did it in normal sql, but when 1'm trying to make the select clause in Code>gniter, it returns null.

How do I know it's null? I have a method where I'm verifying if the result is null. If it is,the controller will show a 404.

Note: The $id from controller it's coming from url.

Codeigniter query:

 public function get_products_from_orders($id){
    $this->db->select('products.product_name');
    $this->db->select('products_to_orders.quantity');
    $this->db->from('products');
    $this->db->from('products_to_orders');
    $this->db->where('products.products_id','products_to_orders.product_id');
    $this->db->where('products_to_orders.order_id',$id);

    $query = $this->db->get();
    return $query->result_array();
}

Normal sql:

$data = $this->db->query("select products.product_name, products_to_orders.quantity
                          from products, products_to_orders
                          where products.products_id = products_to_orders.product_id 
                          and products_to_orders.order_id ='" . $id."'");
return $data;

Controller:

public function view($id = NULL)
{
    $data['products'] = $this->order_model->get_products_from_orders($id);

    if (empty($data['products'])) {
      show_404();
    }
    $this->load->view('templates/header');
    $this->load->view('orders/view',$data);
    $this->load->view('templates/footer');
}

Solution

  • I would use a join clause:

    $this->db->select('products.product_name, products_to_orders.quantity');
    $this->db->from('products');
    $this->db->join('products_to_orders', 'products.products_id=products_to_orders.product_id');
    
    $this->db->where('products_to_orders.order_id',$id);
    
    $query = $this->db->get();
    return $query->result_array();
    

    see CI documentation on joins here

    see MySQL docs on joins here