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

CodeIgniter中设置采购表关联已有客户ID报错问题排查

解决CodeIgniter中客户ID赋值错误的问题

嘿,我看到你在处理已有客户关联采购单ID时遇到了这个对象转字符串的错误,这是新手用CodeIgniter数据库类很容易踩的坑,我来帮你捋清楚问题和解决方法。

错误原因

在else分支里,$cust = $this->db->select('cust_id')->where($array)->get('customer');这行代码返回的是CI_DB_mysqli_result查询结果对象,而不是你需要的具体cust_id数值。当你把这个对象直接赋值给$purchase['cust_id']然后插入数据库时,PHP就会报错——因为数据库字段需要的是字符串/数字类型,不是对象。

修复后的代码

还有个小优化点:你前面已经通过$query = $this->db->get('customer');拿到了查询结果,没必要再执行一次相同条件的查询,直接复用之前的结果就好,能提升代码效率。修改后的代码如下:

Class Entry_m extends CI_Controller{ 
    public function create_submit($customer, $purchase){ 
        $array = array('lname' => $customer['lname'], 'fname' => $customer['fname'], 'mn' => $customer['mn']); 
        $this->db->like($array); 
        $query = $this->db->get('customer'); 
        $count = $query->num_rows(); 
        if($count === 0) { 
            $this->db->insert('customer', $customer); 
            $cust_id = $this->db->insert_id(); 
            $purchase['cust_id'] = $cust_id; 
            $this->db->insert('purchase', $purchase); 
            return $cust_id; // 原代码重复赋值insert_id有误,这里返回刚插入的客户ID即可
        }else{ 
            // 从已有的查询结果中取出客户ID
            $cust_row = $query->row(); // 获取单条结果的对象
            $purchase['cust_id'] = $cust_row->cust_id; 
            // 也可以用数组形式获取:$cust_array = $query->row_array(); $purchase['cust_id'] = $cust_array['cust_id'];
            $this->db->insert('purchase', $purchase); 
            // 若需要返回客户ID,可加上return $cust_row->cust_id;
        } 
    } 
}

额外说明

  1. row()方法会返回查询结果的第一条记录作为对象,你可以通过->字段名的方式获取值;如果习惯用数组,就用row_array(),通过['字段名']获取。
  2. 原代码if分支里的return $cust_id = $this->db->insert_id();存在逻辑问题:insert_id()在插入customer后拿到的是客户ID,插入purchase后拿到的是采购单ID,这里你应该返回的是客户ID,所以直接return $cust_id;就对了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:41:03