【问题标题】:multiple table select with codeigniter使用 codeigniter 进行多表选择
【发布时间】:2015-09-17 08:28:23
【问题描述】:

我有一个包含订单详细信息(如 id、日期等)的“订单”表和一个包含 (order_id,product_id) 的表“订单产品”

我想做一个 SELECT,它会返回一个数组,里面有一个包含所有产品 ID 的数组

示例:$array=(id,date,...,array products(id1,id2...))

这是我的代码:

public function get_order_single($id)
{
     $query = $this->db->select( '
                orders.id,
                orders.customer_id AS customerID,
                orders.date,
                orders.payment_method AS paymentMethod,
                orders.total_price AS totalPrice,
                orders.delivery_address AS address,
                orders.modified,
                orders.created')
                ->from( 'orders' )
                ->where('id',$id)
                ->get()
                ->result( 'array' );    
    return $query[0];
}

我需要添加什么才能从第二个表中获取所有信息?

【问题讨论】:

    标签: php mysql codeigniter select


    【解决方案1】:
    public function get_order_single($id)
    {
        // Get your order
        $order = $this->db->select('
                orders.id,
                orders.customer_id AS customerID,
                orders.date,
                orders.payment_method AS paymentMethod,
                orders.total_price AS totalPrice,
                orders.delivery_address AS address,
                orders.modified,
                orders.created')
            ->from('orders')
            ->where('id', $id)
            ->get()
            ->row();
    
        // If order is exists, lets find products for it
        if ($order) {
            // Here we do a join also to your pivot table
            $order->products = $this->db
                ->where_in('order_products.order_id', $order->id)
                ->join('order_products', 'order_products.product_id = products.id', 'left')
                ->get('products')
                ->result();
        }
    
        return $order;
    }
    

    【讨论】:

    • 我使用了对象,但您可以将它们更改为数组:row() -> row_array()result() -> result_array()$order->id -> $order['id']
    【解决方案2】:

    尝试做这样的事情:

    $this->db->select('name, value'); // SELECT which columns you want
    $this->db->join('attribute', 'attribute.id = product_attribute.attribute_id', 'left'); // JOIN 1st table
    $this->db->join('attribute_value', 'attribute_value.attribute_id = product_attribute.attribute_id', 'left'); // JOIN 2nd table
    $this->db->where('product_id', $id); // CONDITION
    $query = $this->db->get('product_attribute'); // FROM clause
    return $query->result();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 2011-08-29
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多