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

CodeIgniter4插入数据报错:Unknown column 'created_at' in 'field list'

CodeIgniter4 插入数据时提示“Unknown column 'created_at' in 'field list'”的解决方案

这个问题的核心是CodeIgniter4的Model类默认启用了自动时间戳处理机制——即使你的代码和数据库表中没有created_at字段,框架也会自动尝试向数据库插入created_at和updated_at字段的值,从而触发字段不存在的错误。

方法1:关闭自动时间戳功能

在对应的模型类(比如PurchaseOrderModel)中添加$useTimestamps = false;配置,彻底关闭框架的自动时间戳处理:

<?php
namespace App\Models;

use CodeIgniter\Model;

class PurchaseOrderModel extends Model
{
    protected $table = 'your_table_name'; // 替换为你的实际表名
    protected $primaryKey = 'id';
    protected $allowedFields = ['field1', 'field2', 'your_timestamp_field']; // 仅包含表中实际存在的字段
    protected $useTimestamps = false; // 关闭自动时间戳
}

方法2:自定义时间戳字段名(如果需要时间戳功能)

如果你的表中有自定义的时间戳字段(比如order_created_at),可以通过配置指定字段名,替代框架默认的created_at/updated_at:

<?php
namespace App\Models;

use CodeIgniter\Model;

class PurchaseOrderModel extends Model
{
    protected $table = 'your_table_name';
    protected $primaryKey = 'id';
    protected $allowedFields = ['field1', 'field2', 'order_created_at', 'order_updated_at'];
    protected $useTimestamps = true; // 保持时间戳功能开启
    protected $createdField = 'order_created_at'; // 自定义创建时间字段
    protected $updatedField = 'order_updated_at'; // 自定义更新时间字段
}

额外检查

  • 确认控制器中实例化的是你配置好的PurchaseOrderModel,而非默认的Model类:
    // PurchaseOrderController中的代码
    $purchaseOrder = new \App\Models\PurchaseOrderModel();
    $purchaseOrder->create($data2);
    
  • 核对$allowedFields数组,确保没有误添加created_at字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 12:59:15