Codeigniter 4 – Modeling Data and ORM (Object-Relational Mapping) with Example

Modeling Data

- In CodeIgniter 4, models are used to interact with the database.
- Models can be used to perform CRUD (Create, Read, Update, Delete) operations.

Creating a Model

- Create a new file in the app/Models directory.
- Extend the CodeIgniter\Model class.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
}

ORM (Object-Relational Mapping)

- ORM is a technique used to interact with the database using objects.
- In CodeIgniter 4, ORM is implemented using the Entity class.

Creating an Entity

- Create a new file in the app/Entities directory.
- Extend the CodeIgniter\Entity class.

Example:

namespace App\Entities;

use CodeIgniter\Entity;

class User extends Entity
{
    protected $datamap = [
        'id' => 'int',
        'name' => 'string',
        'email' => 'string',
    ];
}

Retrieving Data

- Use the find() method to retrieve data from the database.

Example:

$user = new User();
$data = $user->find(1);

Creating Data

- Use the insert() method to create new data in the database.

Example:

$user = new User();
$user->insert([
    'name' => 'John Doe',
    'email' => 'john@example.com',
]);

Updating Data

- Use the update() method to update existing data in the database.

Example:

$user = new User();
$user->update(1, [
    'name' => 'Jane Doe',
]);

Deleting Data

- Use the delete() method to delete data from the database.

Example:

$user = new User();
$user->delete(1);

I hope this helps! Let me know if you have any further questions or need more information.

Note: Modeling data and using ORM in CodeIgniter 4 provides a simple and intuitive way to interact with the database. It helps to keep the code organized and maintainable.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0