CodeIgniter4作为轻量高效的PHP框架,其模型层结合Active Record模式能大幅简化数据库操作逻辑,开发者无需编写复杂的原生SQL语句即可完成各类数据交互需求。

一、CodeIgniter4模型基础配置
首先需要创建对应的模型类,模型文件通常放在app/Models目录下,基础模型需要继承CodeIgniterModel类,同时配置对应的数据表名和主键信息。
以下是一个用户表模型的基础示例:
<?php
namespace AppModels;
use CodeIgniterModel;
class UserModel extends Model {
// 指定对应的数据表名
protected $table = 'users';
// 指定表的主键字段
protected $primaryKey = 'id';
// 允许批量赋值的字段
protected $allowedFields = ['username', 'email', 'password'];
// 开启自动维护时间戳,会自动填充created_at和updated_at字段
protected $useTimestamps = true;
// 时间戳字段的格式
protected $dateFormat = 'datetime';
}
二、Active Record查询操作
Active Record模式通过链式调用方法构建查询条件,最终执行查询获取结果,无需手动拼接SQL字符串。
1. 查询所有数据
直接调用模型的findAll方法即可获取表中所有数据:
<?php
// 在控制器中调用模型
$model = new AppModelsUserModel();
// 获取所有用户数据
$users = $model->findAll();
// 遍历输出结果
foreach ($users as $user) {
echo $user['username'] . '<br>';
}
2. 条件查询
使用where方法添加查询条件,支持多种条件组合:
<?php
$model = new AppModelsUserModel();
// 查询邮箱为test@ipipp.com的用户
$user = $model->where('email', 'test@ipipp.com')->first();
// 查询年龄大于18且状态为1的用户
$adultUsers = $model->where('age >', 18)->where('status', 1)->findAll();
// 模糊查询用户名包含admin的用户
$adminUsers = $model->like('username', 'admin')->findAll();
3. 排序与分页
通过orderBy实现排序,paginate实现分页查询:
<?php
$model = new AppModelsUserModel();
// 按创建时间倒序查询前10条数据
$latestUsers = $model->orderBy('created_at', 'DESC')->limit(10)->findAll();
// 分页查询,每页显示15条数据,返回分页数据和分页链接
$pageUsers = $model->paginate(15);
$pager = $model->pager;
三、Active Record写入与更新操作
1. 插入数据
使用insert方法插入单条数据,insertBatch插入多条数据:
<?php
$model = new AppModelsUserModel();
// 插入单条用户数据
$data = [
'username' => 'new_user',
'email' => 'new@ipipp.com',
'password' => password_hash('123456', PASSWORD_DEFAULT)
];
$model->insert($data);
// 获取插入的自增ID
$newId = $model->getInsertID();
// 批量插入数据
$batchData = [
['username' => 'user1', 'email' => 'user1@ipipp.com', 'password' => 'pass1'],
['username' => 'user2', 'email' => 'user2@ipipp.com', 'password' => 'pass2']
];
$model->insertBatch($batchData);
2. 更新数据
使用update方法更新数据,需要先指定更新条件:
<?php
$model = new AppModelsUserModel();
// 更新ID为5的用户邮箱
$model->update(5, ['email' => 'updated@ipipp.com']);
// 条件更新,更新所有状态为0的用户状态为1
$model->where('status', 0)->set(['status' => 1])->update();
四、Active Record删除操作
删除操作使用delete方法,支持单条删除和批量删除:
<?php
$model = new AppModelsUserModel();
// 删除ID为3的用户
$model->delete(3);
// 删除年龄小于18的用户
$model->where('age <', 18)->delete();
// 批量删除ID为1,2,3的用户
$model->delete([1,2,3]);
五、注意事项
- 使用Active Record操作前需要确保数据库配置正确,配置文件位于
app/Config/Database.php,默认连接本地127.0.0.1的数据库。 - 插入和更新数据时,字段必须在
allowedFields数组中定义,否则会被过滤无法写入。 - 涉及用户输入的条件值建议通过参数绑定方式传递,避免SQL注入风险,Active Record内部已经做了参数转义处理。
- 如果不需要自动维护时间戳,可以将
useTimestamps设置为false。
CodeIgniter4Active_RecordPHP数据库操作修改时间:2026-07-03 01:09:29