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

CodeIgniter模型报错:Call to a member function row() on bool问题排查

错误分析与解决方案:Call to a member function row() on bool

错误详情

类型: Error
信息: Call to a member function row() on bool
文件: application/models/Ledger_model.php
行号: 47
调用栈:

  • 文件:application/controllers/Purchase.php 行:56 方法:get_branch_from_ledger_id
  • 文件:index.php 行:315 方法:require_once

问题根源

先看触发错误的代码段(Ledger_model.php第42-47行):

function get_branch_from_ledger_id($id) {
    return $this->db->select('l.*,a.branch_id')
    ->from('ledger l')
    ->join('account_group a','a.id = l.accountgroup_id')
    ->where('l.id',$id)
    ->get()
    ->row()
    ->branch_id;
}

这里的核心问题是没有任何错误判断的链式调用,两种场景都会触发报错:

  1. 数据库查询执行失败:比如ledger/account_group表不存在、字段拼写错误、数据库权限不足,或者传入的$id是非法值(比如null、非数字),导致$this->db->get()直接返回false,此时调用row()就会抛出Call to a member function row() on bool。
  2. 无匹配记录:如果传入的$id在ledger表中不存在,或者对应的ledger记录的accountgroup_id在account_group表中找不到匹配项,查询结果为空。虽然此时get()会返回CI的结果对象,但row()会返回null,后续调用->branch_id也会报错(你的错误提示指向row(),所以更可能是第一种情况)。

修复方案

我们需要给这个方法加上完整的错误校验,同时优化查询(只获取需要的字段):

修复后的代码

function get_branch_from_ledger_id($id) {
    // 第一步:校验传入的ID合法性
    if (empty($id) || !is_numeric($id)) {
        return false;
    }

    // 执行查询,先获取查询对象
    $query = $this->db->select('a.branch_id') // 只查询需要的字段,提升性能
                      ->from('ledger l')
                      ->join('account_group a', 'a.id = l.accountgroup_id')
                      ->where('l.id', $id)
                      ->get();

    // 第二步:检查查询是否成功
    if (!$query) {
        // 记录错误日志,方便后续排查
        log_message('error', 'Query failed in get_branch_from_ledger_id: ' . json_encode($this->db->error()));
        return false;
    }

    // 第三步:获取单条记录并检查是否存在
    $record = $query->row();
    if (!$record || !isset($record->branch_id)) {
        return false;
    }

    return $record->branch_id;
}

额外排查建议

  • 检查数据库中ledger和account_group表的结构,确认ledger.accountgroup_id和account_group.id字段存在且数据类型匹配(比如都是INT类型);
  • 查看CodeIgniter的日志文件(默认在application/logs/目录),里面会有更详细的数据库错误信息,帮助定位问题;
  • 在调用这个方法的Purchase.php第56行,先校验传入的ID是否有效,避免传入空值或非法值;
  • 可以临时在查询后添加echo $this->db->last_query(); exit;,把生成的SQL语句拿到数据库客户端执行,看是否能得到预期结果或报错。

内容的提问来源于stack exchange,提问作者Kamlesh Kumar Kushwaha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 00:37:32