bertugfahriozer/ci4commonmodel

使用CodeIgniter 4数据库构建器,我将为自己使用的通用方法结合成一个单一模型。

1.1.11 2024-09-15 21:41 UTC

This package is auto-updated.

Last update: 2024-09-15 21:42:14 UTC


README

CommonModel 是一个适用于CodeIgniter 4的通用和可重用模型,旨在简化常见的数据库操作,如选择、插入、更新和删除记录。此库提供支持常见SQL功能的方法,如JOIN、WHERE条件、LIKE过滤和排序。

功能

安装

要在您的CodeIgniter 4项目中使用 CommonModel,请按照以下步骤操作

  1. 使用Composer在您的项目中安装

    composer require bertugfahriozer/ci4commonmodel
  2. 在您的控制器中加载模型

    use ci4commonmodel\Models\CommonModel;
    
    class ExampleController extends BaseController
    {
        protected $commonModel;
    
        public function __construct()
        {
            $this->commonModel = new CommonModel();
        }
    }

用法

1. 获取记录(lists

lists 方法允许您通过灵活的过滤器从数据库表中获取记录,如WHEREOR WHERELIKEJOIN和排序。可选地,可以应用限制和分页。

$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文件。

作者

Bertuğ Fahri ÖZER