codeigniter购物车和多个表

时间:2012-02-20 03:37:32

标签: mysql database codeigniter shopping-cart

我对codeigniter很新,我想更好地了解数据库,所以我决定关注this guide

但是我想要更高级一点并尝试使用多个表的多个页面,我有一半工作但是当我点击添加到购物车时它始终从数据库1中选择项目。它使用

$this->db->where('id', $id);  
$query = $this->db->get('fruit', 1);  

将商品添加到购物车。但我希望它能够从多个表中选择,例如。水果和蔬菜,他们都在不同的表,但有相同的列,无论如何使用连接或任何其他方法轻松做到这一点?

1 个答案:

答案 0 :(得分:1)

是的,你看看codeigniter active record吗?

Something like?
$this->db->select('*');
$this->db->from('fruit');
$this->db->join('veg', 'fruit.id = veg.id');

$query = $this->db->get();

// Produces:
// SELECT * FROM fruit
// JOIN veg ON veg.id = fruit.id

编辑:    根据您在评论中的描述,我构建了这两个表格。

   mysql> desc fruit;
   +-------+-------------+------+-----+---------+-------+
   | Field | Type        | Null | Key | Default | Extra |
   +-------+-------------+------+-----+---------+-------+
   | id    | int(11)     | NO   |     | NULL    |       |
   | name  | varchar(29) | NO   |     | NULL    |       |
   | price | int(11)     | YES  |     | NULL    |       |
   +-------+-------------+------+-----+---------+-------+
   3 rows in set (0.00 sec)

   mysql> desc veg;
   +-------+-------------+------+-----+---------+-------+
   | Field | Type        | Null | Key | Default | Extra |
   +-------+-------------+------+-----+---------+-------+
   | id    | int(11)     | NO   |     | NULL    |       |
   | name  | varchar(20) | NO   |     | NULL    |       |
   | price | int(11)     | YES  |     | NULL    |       |
   +-------+-------------+------+-----+---------+-------+
   3 rows in set (0.00 sec)

这是使用多个和连接的函数测试的示例。我想这是你最后的SQL查询?

SELECT *
FROM (`fruit`)
JOIN `veg` ON `fruit`.`id` = `veg`.`id` and fruit.name = veg.name and fruit.price = veg.price
WHERE `fruit`.`id` =  1

这是相应的codeigniter查询。

public function testJoins() {
    $id = 1;
    $this->db->select('*');
    $this->db->from('fruit');
    $this->db->join('veg', 'fruit.id = veg.id and fruit.name = veg.name and fruit.price = veg.price');
    $this->db->where('fruit.id', $id);

    $query = $this->db->get();
    return $query->result();
}
相关问题