You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter的where()关联数组中比较两个表字段

解决CodeIgniter查询构造器中WHERE子句关联表字段的问题

嘿,我完全懂你碰到的这个坑——在CodeIgniter的查询构造器里,直接用键值对数组写跨表字段对比时,框架会把右侧的字段名当成普通字符串处理,所以才会出现r.RewardID = 'cor.RewardID'这种错误的SQL。

问题根源

你当前的where数组写法"r.RewardID" => "cor.RewardID",框架会默认把cor.RewardID视为一个字符串值,自动给它加上单引号,导致它无法作为关联表的字段被解析。

正确的解决方法

有几种方式可以实现跨表字段的对比:

方法1:直接传递WHERE表达式字符串

把字段对比的逻辑直接写成SQL表达式字符串传给where()方法,框架会原样保留这个表达式:

$item = $this->db->select("r.CustomerIDs, r.DateAdded")
    ->join("customer_orders_rewards as cor", "r.RewardID = cor.RewardID")
    ->join("customer_orders as co", "co.OrderID = cor.OrderID")
    ->where("r.Denomination", $row['Denomination'])
    ->where("r.RewardID = cor.RewardID") // 直接写字段对比逻辑
    ->get("customer_rewards as r");

方法2:使用数组形式配合NULL值

如果偏好数组写法,可以把字段对比的表达式作为数组的键,值设为NULL,这样框架就不会把它当成字符串值处理:

$item = $this->db->select("r.CustomerIDs, r.DateAdded")
    ->join("customer_orders_rewards as cor", "r.RewardID = cor.RewardID")
    ->join("customer_orders as co", "co.OrderID = cor.OrderID")
    ->where([
        "r.Denomination" => $row['Denomination'],
        "r.RewardID = cor.RewardID" => NULL
    ])
    ->get("customer_rewards as r");

方法3:关闭自动转义(可选)

如果需要更明确地控制,可以在where()方法中传入第三个参数FALSE,关闭自动转义,确保表达式被正确解析:

$item = $this->db->select("r.CustomerIDs, r.DateAdded")
    ->join("customer_orders_rewards as cor", "r.RewardID = cor.RewardID")
    ->join("customer_orders as co", "co.OrderID = cor.OrderID")
    ->where("r.Denomination", $row['Denomination'])
    ->where("r.RewardID = cor.RewardID", NULL, FALSE)
    ->get("customer_rewards as r");

小提醒

另外注意一下,你已经在join条件里写了r.RewardID = cor.RewardID,这个WHERE条件其实和JOIN的条件重复了,可能可以去掉?不过如果是有特殊的过滤需求,那就按你的实际场景来就好。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:28:30