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

如何用CodeIgniter查询构造器根据某行value获取同var_id的其他行

CodeIgniter 查询构造器实现方案

以下两种写法兼容 CodeIgniter 3 和 CodeIgniter 4 版本,你可以根据自己的使用场景选择:

方案1:子查询一次性查询(性能更高)

仅需一次数据库请求,适合生产环境使用:

// 替换为你实际查询的唯一value值
$target_value = '#cfcfcf';
// 替换为你自己的数据库表名
$table_name = '你的表名';

// 编译子查询语句:查询指定value对应的var_id
$sub_query = $this->db->select('var_id')
    ->from($table_name)
    ->where('value', $target_value)
    ->get_compiled_select();

// 执行主查询:获取所有同var_id的行数据
$result = $this->db->from($table_name)
    ->where("var_id = ($sub_query)", NULL, FALSE)
    ->get()
    ->result();

说明:where方法第三个参数设为FALSE是为了避免CI自动转义子查询语句的括号,保证语法正确。如果需要返回数组格式的结果,可以把result()替换为result_array()。

方案2:分两次查询(逻辑直观易调试)

适合新手理解,调试成本更低:

$target_value = '#cfcfcf';
$table_name = '你的表名';

// 第一步:查询指定value对应的var_id
$var_info = $this->db->select('var_id')
    ->from($table_name)
    ->where('value', $target_value)
    ->get()
    ->row();

$result = [];
if (!empty($var_info)) {
    // 第二步:根据var_id查询所有关联行
    $result = $this->db->from($table_name)
        ->where('var_id', $var_info->var_id)
        ->get()
        ->result();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:36:00