You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用CodeIgniter Active Record的where()方法比较两个列

没问题,我来帮你搞定这个CodeIgniter Active Record的列比较问题!先理清楚你的数据表结构,然后一步步说明怎么实现:


你的数据表结构

products

products_idproduct_name
1Pizza x
2Pizza Y
3Pizza A
4Pizza Z
5Pizza W

order_items 表(假设这是你的订单明细表)

idproducts_idorder_idquantity
1153
1254
2363
2463
3572

使用CodeIgniter Active Record实现列比较的方法

CodeIgniter的where()方法默认是用来匹配字段和固定值的,但如果要比较两个数据库列,你需要直接传入完整的SQL比较表达式,并且通过第三个参数false告诉框架不要对表达式里的列名进行转义(避免把列名当成字符串值处理)。

场景1:单表内的列比较

比如你想查询order_items表中id等于products_id的记录:

$this->db->select('*');
$this->db->from('order_items');
// 直接传入列比较的SQL表达式,第三个参数false关闭自动转义
$this->db->where('id = products_id', null, false);
$query = $this->db->get();

// 获取查询结果
$results = $query->result();

场景2:多表关联时的列比较

如果需要关联productsorder_items表,并用where()匹配两个表的products_id列(虽然更规范的做法是用join条件,但这里演示where的用法):

$this->db->select('p.product_name, oi.order_id, oi.quantity');
$this->db->from('products p');
$this->db->join('order_items oi', '1=1'); // 先建立表关联
// 比较两个表的products_id列
$this->db->where('p.products_id = oi.products_id', null, false);
$query = $this->db->get();

$results = $query->result();

当然,多表关联更推荐直接在join里写列比较条件,代码更清晰:

$this->db->select('p.product_name, oi.order_id, oi.quantity');
$this->db->from('products p');
// 直接在join中指定列匹配规则
$this->db->join('order_items oi', 'p.products_id = oi.products_id');
$query = $this->db->get();

$results = $query->result();

关键注意点

  • 不要用$this->db->where('column1', 'column2')这种写法,框架会把column2当成字符串值,生成的SQL会是WHERE column1 = 'column2',这完全不是你要的列比较效果。
  • 必须把完整的比较表达式作为第一个参数传入where(),同时设置第三个参数为false,这样框架才会保留原始的列名,生成正确的WHERE column1 = column2语句。

内容的提问来源于stack exchange,提问作者Mitca Vicentiu

火山引擎 最新活动