bertugfahriozer / ci4commonmodel
使用CodeIgniter 4数据库构建器,我将为自己使用的通用方法结合成一个单一模型。
1.1.11
2024-09-15 21:41 UTC
Requires
- php: ^7.3||^8.0
README
CommonModel
是一个适用于CodeIgniter 4的通用和可重用模型,旨在简化常见的数据库操作,如选择、插入、更新和删除记录。此库提供支持常见SQL功能的方法,如JOIN、WHERE条件、LIKE过滤和排序。
功能
-
选择记录,带有灵活的条件(
WHERE
、OR WHERE
、LIKE
) -
插入单个或多个记录到数据库
-
根据条件更新和删除记录
-
连接表以进行更复杂的查询
-
支持 排序 和 分页
-
轻松进行 计数 和记录的 存在性检查
-
内置对 LIKE 查询和 批量操作 的支持
安装
要在您的CodeIgniter 4项目中使用 CommonModel
,请按照以下步骤操作
-
使用Composer在您的项目中安装
composer require bertugfahriozer/ci4commonmodel
-
在您的控制器中加载模型
use ci4commonmodel\Models\CommonModel; class ExampleController extends BaseController { protected $commonModel; public function __construct() { $this->commonModel = new CommonModel(); } }
用法
1. 获取记录(lists
)
lists
方法允许您通过灵活的过滤器从数据库表中获取记录,如WHERE
、OR WHERE
、LIKE
、JOIN
和排序。可选地,可以应用限制和分页。
$data = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'status' => 1 ]; $insertId = $this->commonModel->create('users', $data);
2. 插入记录(create
)
将单个记录插入数据库并返回新插入的ID。
$data = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'status' => 1 ]; $insertId = $this->commonModel->create('users', $data);
3. 批量插入(createMany
)
使用createMany方法一次性插入多个记录。
$data = [ ['name' => 'Alice', 'email' => 'alice@example.com'], ['name' => 'Bob', 'email' => 'bob@example.com'] ]; $this->commonModel->createMany('users', $data);
4. 更新记录(edit
)
通过指定WHERE条件和新数据来更新现有记录。
$data = ['status' => 2]; $where = ['id' => 1]; $this->commonModel->edit('users', $data, $where);
5. 删除记录(remove
)
根据WHERE条件从表中删除记录。
$where = ['id' => 1]; $this->commonModel->remove('users', $where);
6. 计数记录(count
)
计算匹配给定条件的记录数量。
$where = ['status' => 1]; $count = $this->commonModel->count('users', $where);
7. 检查记录存在(isHave
)
检查是否在表中存在具有指定条件的记录。
$where = ['id' => 1]; $isExist = $this->commonModel->isHave('users', $where);
8. 复杂查询(research
)
使用research通过LIKE查询搜索记录并按条件过滤。
$like = ['name' => 'John']; $where = ['status' => 1]; $results = $this->commonModel->research('users', $like, '*', $where);
许可证
本项目采用MIT许可证。有关详细信息,请参阅LICENSE文件。