PHPackages                             bertugfahriozer/ci4commonmodel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. bertugfahriozer/ci4commonmodel

ActiveLibrary[Database &amp; ORM](/categories/database)

bertugfahriozer/ci4commonmodel
==============================

With the codeigniter 4 database builder, I combined the general methods I used for myself into a single model.

1.2.5(1mo ago)380212MITPHPPHP ^7.4||^8.0CI passing

Since Jan 22Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/bertugfahriozer/ci4commonModel)[ Packagist](https://packagist.org/packages/bertugfahriozer/ci4commonmodel)[ RSS](/packages/bertugfahriozer-ci4commonmodel/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)DependenciesVersions (21)Used By (2)

CommonModel Library for CodeIgniter 4
=====================================

[](#commonmodel-library-for-codeigniter-4)

`CommonModel` is a versatile and reusable model for CodeIgniter 4, designed to simplify common database operations such as selecting, inserting, updating, and deleting records. This library provides methods that support common SQL features like JOINs, WHERE conditions, LIKE filters, ordering, and more.

Features
--------

[](#features)

- Multiple Database Connection Groups
- **Select records** with flexible conditions (`WHERE`, `OR WHERE`, `LIKE`)
- **Insert single or multiple records** into the database
- **Update and delete** records based on conditions
- **Join tables** for more complex queries
- Supports **ordering** and **pagination**
- Easy **counting** and **existence checks** for records
- Built-in support for **like** queries and **batch operations**
- Table and column management (add, remove, modify)
- Database creation and deletion

Table of Contents
-----------------

[](#table-of-contents)

- [CommonModel Library for CodeIgniter 4](#commonmodel-library-for-codeigniter-4)
    - [Features](#features)
    - [Table of Contents](#table-of-contents)
    - [Installation](#installation)
    - [Usage](#usage)
        - [1. Retrieving Records (`lists`)](#1-retrieving-records-lists)
        - [2. Inserting Records (`create`)](#2-inserting-records-create)
        - [3. Batch Insert (`createMany`)](#3-batch-insert-createmany)
        - [4. Updating Records (`edit`)](#4-updating-records-edit)
        - [5. Deleting Records (`remove`)](#5-deleting-records-remove)
        - [6. Count Records (`count`)](#6-count-records-count)
        - [7. Check Record Existence (`isHave`)](#7-check-record-existence-ishave)
        - [8. Complex Queries (`research`)](#8-complex-queries-research)
        - [9. Table and Database Management](#9-table-and-database-management)
            - [Get Table List](#get-table-list)
            - [Create a New Table](#create-a-new-table)
            - [Remove a Table](#remove-a-table)
            - [Add Column to Table](#add-column-to-table)
            - [Remove Column from Table](#remove-column-from-table)
            - [Rename Table](#rename-table)
            - [Modify Column Info](#modify-column-info)
            - [Truncate Table](#truncate-table)
            - [Get Table Fields](#get-table-fields)
            - [Create a New Database](#create-a-new-database)
            - [Remove a Database](#remove-a-database)
            - [Drop Primary Key](#drop-primary-key)
            - [Drop Key](#drop-key)
            - [Drop Foreign Key](#drop-foreign-key)
    - [Troubleshooting: Multiple Database Connection Groups](#troubleshooting-multiple-database-connection-groups)
        - [Root Cause](#root-cause)
        - [Solution](#solution)
    - [License](#license)
    - [Author](#author)

Installation
------------

[](#installation)

To use `CommonModel` in your CodeIgniter 4 project, follow these steps:

1. Install with Composer:

    ```
    composer require bertugfahriozer/ci4commonmodel
    ```
2. Load the model in your controller:

    ```
    use ci4commonmodel\CommonModel;

    class ExampleController extends BaseController
    {
        protected $commonModel;

        public function __construct()
        {
            $this->commonModel = new CommonModel();
        }
    }
    ```

Usage
-----

[](#usage)

### 1. Retrieving Records (`lists`)

[](#1-retrieving-records-lists)

Fetch records from a database table with flexible filters such as `WHERE`, `OR WHERE`, `LIKE`, `JOIN`, and ordering. Supports limit and pagination.

```
// Simple usage
$users = $this->commonModel->lists('users', '*', ['status' => 1], 'id DESC', 10);

// Advanced usage with JOIN and LIKE
$joins = [
    ['table' => 'roles', 'cond' => 'users.role_id = roles.id', 'type' => 'left']
];
$like = ['name' => 'John'];
$users = $this->commonModel->lists('users', 'users.*, roles.name as role', ['status' => 1], 'users.id DESC', 10, 0, $like, [], $joins);
```

### 2. Inserting Records (`create`)

[](#2-inserting-records-create)

Insert a single record into the database and return the newly inserted ID.

```
$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'status' => 1
];

$insertId = $this->commonModel->create('users', $data);
```

### 3. Batch Insert (`createMany`)

[](#3-batch-insert-createmany)

Insert multiple records at once.

```
$data = [
    ['name' => 'Alice', 'email' => 'alice@example.com'],
    ['name' => 'Bob', 'email' => 'bob@example.com']
];

$this->commonModel->createMany('users', $data);
```

### 4. Updating Records (`edit`)

[](#4-updating-records-edit)

Update existing records by specifying the WHERE conditions and the new data.

```
$data = ['status' => 2];
$where = ['id' => 1];

$this->commonModel->edit('users', $data, $where);
```

### 5. Deleting Records (`remove`)

[](#5-deleting-records-remove)

Delete records from a table based on WHERE conditions.

```
$where = ['id' => 1];
$this->commonModel->remove('users', $where);
```

### 6. Count Records (`count`)

[](#6-count-records-count)

Count the number of records that match a given condition.

```
$where = ['status' => 1];
$count = $this->commonModel->count('users', $where);
```

### 7. Check Record Existence (`isHave`)

[](#7-check-record-existence-ishave)

Check whether a record exists in a table with a specified condition.

```
$where = ['id' => 1];
$isExist = $this->commonModel->isHave('users', $where);
```

### 8. Complex Queries (`research`)

[](#8-complex-queries-research)

Search records using LIKE queries and filtering by conditions.

```
$like = ['name' => 'John'];
$where = ['status' => 1];

$results = $this->commonModel->research('users', $like, '*', $where);
```

### 9. Table and Database Management

[](#9-table-and-database-management)

#### Get Table List

[](#get-table-list)

```
$tables = $this->commonModel->getTableList();
```

#### Create a New Table

[](#create-a-new-table)

```
$fields = [
    'id' => [
        'type' => 'INT',
        'constraint' => 5,
        'unsigned' => true,
        'auto_increment' => true,
    ],
    'title' => [
        'type' => 'VARCHAR',
        'constraint' => '100',
        'unique' => true,
    ]
];
$this->commonModel->newTable('blog', $fields);
```

#### Remove a Table

[](#remove-a-table)

```
$this->commonModel->removeTable('blog');
```

#### Add Column to Table

[](#add-column-to-table)

```
$fields = [
    'preferences' => ['type' => 'TEXT', 'after' => 'email'],
];
$this->commonModel->addColumnToTable('users', $fields);
```

#### Remove Column from Table

[](#remove-column-from-table)

```
$this->commonModel->removeColumnFromTable('users', ['preferences']);
```

#### Rename Table

[](#rename-table)

```
$this->commonModel->updateTableName('old_table', 'new_table');
```

#### Modify Column Info

[](#modify-column-info)

```
$fields = [
    'old_name' => [
        'name' => 'new_name',
        'type' => 'TEXT',
        'null' => false,
    ],
];
$this->commonModel->modifyColumnInfos('users', $fields);
```

#### Truncate Table

[](#truncate-table)

```
$this->commonModel->emptyTableDatas('users');
```

#### Get Table Fields

[](#get-table-fields)

```
$fields = $this->commonModel->getTableFields('users');
```

#### Create a New Database

[](#create-a-new-database)

```
$this->commonModel->newDatabase('new_db');
```

#### Remove a Database

[](#remove-a-database)

```
$this->commonModel->removeDatabase('old_db');
```

#### Drop Primary Key

[](#drop-primary-key)

```
$this->commonModel->drpPrimaryKey('users');
```

#### Drop Key

[](#drop-key)

```
$this->commonModel->drpKey('users', 'my_key_name');
```

#### Drop Foreign Key

[](#drop-foreign-key)

```
$this->commonModel->drpForeignKey('orders', 'fk_orders_users');
```

Troubleshooting: Multiple Database Connection Groups
----------------------------------------------------

[](#troubleshooting-multiple-database-connection-groups)

When working with multiple database connections in CodeIgniter 4, defining them in the `.env` file is not sufficient on its own. Here's an example configuration in `.env`:

```
database.default.hostname=127.0.0.1
database.default.database=giritliadali
database.default.username=root
database.default.password=root
database.default.DBDriver=MySQLi
database.default.port=3306

database.secondDB.hostname=127.0.0.1
database.secondDB.database=giritliadali_bac
database.secondDB.username=root
database.secondDB.password=root
database.secondDB.DBDriver=MySQLi
database.secondDB.port=3306
```

Attempting to connect using:

```
$this->db = \Config\Database::connect('secondDB');
```

Will result in the error:

```

"secondDB" is not a valid database connection group.

```

### Root Cause

[](#root-cause)

CodeIgniter 4 does not auto-load database groups other than `default` from the `.env` file. You must explicitly define custom groups like `secondDB` in the `app/Config/Database.php` file.

### Solution

[](#solution)

To fix this, add a new public array in your `app/Config/Database.php`:

```
public array $secondDB = [
        'DSN'          => '',
        'hostname'     => 'localhost',
        'username'     => '',
        'password'     => '',
        'database'     => '',
        'DBDriver'     => 'MySQLi',
        'DBPrefix'     => '',
        'pConnect'     => false,
        'DBDebug'      => true,
        'charset'      => 'utf8mb4',
        'DBCollat'     => 'utf8mb4_general_ci',
        'swapPre'      => '',
        'encrypt'      => false,
        'compress'     => false,
        'strictOn'     => false,
        'failover'     => [],
        'port'         => 3306,
        'numberNative' => false,
        'foundRows'    => false,
        'dateFormat'   => [
            'date'     => 'Y-m-d',
            'datetime' => 'Y-m-d H:i:s',
            'time'     => 'H:i:s',
        ],
    ];
```

Once added, `\Config\Database::connect('secondDB')` will work properly.

License
-------

[](#license)

This project is licensed under the MIT License. See the [LICENSE](https://opensource.org/license/mit) file for more details.

Author
------

[](#author)

[Bertuğ Fahri ÖZER](https://github.com/bertugfahriozer)

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance93

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~67 days

Recently: every ~89 days

Total

19

Last Release

36d ago

PHP version history (2 changes)1.0.0PHP ^7.3||^8.0

1.2.0PHP ^7.4||^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/20905215?v=4)[Bertuğ Fahri ÖZER](/maintainers/bertugfahriozer)[@bertugfahriozer](https://github.com/bertugfahriozer)

---

Top Contributors

[![bertugfahriozer](https://avatars.githubusercontent.com/u/20905215?v=4)](https://github.com/bertugfahriozer "bertugfahriozer (36 commits)")

---

Tags

batch-insertcodeigniter-crudcodeigniter-librarycodeigniter-modelcodeigniter4cruddatabasedatabase-managementjoinlibrarylike-querymigrationmodelopen-sourcephpquery-buildertable-managementwhere

### Embed Badge

![Health badge](/badges/bertugfahriozer-ci4commonmodel/health.svg)

```
[![Health](https://phpackages.com/badges/bertugfahriozer-ci4commonmodel/health.svg)](https://phpackages.com/packages/bertugfahriozer-ci4commonmodel)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k116.5M113](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
