【问题标题】:codeigniter query always returns nullcodeigniter 查询总是返回 null
【发布时间】:2018-09-18 01:09:05
【问题描述】:

我有这两张表:

+-------------+--------------+
| 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 |
+----+-------------+----------+----------+

我想为每个 order_id 选择 products_namequantity。我是用普通sql做的,但是当1试图在Codeigniter中做select子句时,它返回null。

我怎么知道它是空的?我有一个方法来验证结果是否为空。如果是,控制器将显示 404。

注意:控制器的 $id 来自 url。

Codeigniter 查询:

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

普通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;

控制器:

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');
}

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    我会使用连接子句:

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

    请参阅有关联接的 CI 文档here

    请参阅有关连接的 MySQL 文档here

    【讨论】:

    • 谢谢,伙计!我不太擅长 join 和 concat ......这就是我没有使用它的原因,但我认为我应该更频繁地使用它们
    猜你喜欢
    • 2021-01-15
    • 2019-11-26
    • 1970-01-01
    • 2018-03-15
    • 2019-04-20
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多