# Models

Models in PHPFast handle database interactions, including querying, inserting, updating, and deleting records. To simplify these operations, PHPFast offers a `BaseModel`, which your models can extend to leverage built-in database functionalities efficiently.

In this section, we will explore the `BaseModel` class, which serves as the foundation for database operations in the PHPFast framework. It provides essential methods for interacting with the database, including querying, inserting, updating, and deleting records, making it easier for other models to manage data efficiently.

## Create Models via Command

This command creates a new model file in the `application/Models` directory.

* The generated model includes a default template with the `_schema()` method.
* It helps define the database table’s structure and provides basic CRUD (Create, Read, Update, Delete) functions.

**Command:**

```sh
php init Models <model_name>

// Example: php init models Users
```

This creates `UsersModel.php` inside `application/Model/`.

## Accessing Model

```php
<?php
use App\Models\UsersModel;

$usersModel = new UsersModel();
```

## Configuration

To switch between database drivers, update the `db_driver` setting in `application/Config/Config.php`

```php
'db' => [
    'db_driver'   => 'mysql',
    'db_host'     => 'localhost',
    'db_port'     => 3306,
    'db_username' => 'root',
    'db_password' => '',
    'db_database' => 'cms.vn',
    'db_charset'  => 'utf8mb4',
    'db_collate'  => 'utf8mb4_unicode_ci',
],
```

## **Example Usage**

```php
<?php
namespace App\Models;
use System\Core\BaseModel;

class UsersModel extends BaseModel {
    protected $table = 'users';
    protected $fillable = ['username', 'email', 'password', 'fullname'];
    protected $guarded = ['id', 'created_at', 'updated_at'];
    
    protected function _schema()
    {
        return [
            'id'           => 'int',
            'username'     => 'string',
            'email'        => 'string',
            'created_at'   => 'timestamp',
            ...            => interface
        ];
    }
    
    protected function _table() {
        return 'users'; // Defines that this model works with the 'users' table
    }
    
    public function getUsers($where = '', $params = [], $orderBy = 'id DESC', $limit = null, $offset = null) {
        return $this->list($this->table, $where, $params, $orderBy, $limit, $offset);
    }
    

    public function getUserById($id){
        return $this->row($this->table, 'id = ?', [$id]);
    }
    
    public function getUsersPage($where = '', $params = [], $orderBy = 'id DESC', $page = 1, $limit = null) {
        return $this->listpaging($this->table, $where, $params, $orderBy, $page, $limit);
    }
    
    public function addUser($data) {
        $data = $this->fill($data);
        return $this->add($this->table, $data);
    }
    
    public function updateUser($id, $data) {
        $data = $this->fill($data);
        return $this->set($this->table, $data, 'id = ?', [$id]);
    }
    
    public function deleteUser($id) {
        return $this->del($this->table, 'id = ?', [$id]);
    }
}
```

**List of Common Methods in a Model (Example in UsersModel):**

#### **Model Configuration and Schema**

* `_schema()`: Defines the database schema for the `users` table, specifying columns, data types, and constraints.

#### **Retrieving User Data**

* `getUsers()`: Retrieves a list of all users from the `users` table, with optional filtering conditions.
* `getUsersPage($where, $params, $orderBy, $page, $limit)`: Retrieves a paginated list of users.
* `getFieldUsersPage($fields, $where, $params, $orderBy, $page, $limit)`: Retrieves a paginated list of users but only fetches specific fields.
* `getUserById($id)`: Retrieves detailed user information based on `ID`.
* `getUserByIdField($fields, $id)`: Retrieves specific fields of a user based on `ID`.
* `getUserByUsername($username)`: Finds a user based on `username`.
* `getUserByEmail($email)`: Finds a user based on `email`.

#### **Managing User Data (Add, Update, Delete)**

* `addUser($data)`: Adds a new user to the `users` table.
* `updateUser($id, $data)`: Updates user information based on `ID`.
* `deleteUser($id)`: Deletes a user from the system based on `ID`.

**Advanced Functions**

* `searchUser($conditions)`: Searches for users based on different criteria using flexible conditions.
* `getLocation($userId)`: Retrieves the geographical location (`longitude`, `latitude`) of a user based on their `ID`, if valid location data exists.

## Model in Controller

```php
<?php
namespace App\Controllers;

use System\Core\BaseController;
use App\Models\UsersModel;

class UsersController extends BaseController
{
    protected $usersModel;

    public function __construct() {
        $this->usersModel = new UsersModel();
    }

    public function index() {
        $users = $this->usersModel->getUsers();
        $this->render('users/index', ['users' => $users]);
    }
    
    public function profile() {
        $id = S_GET('id') ?? ''; 
        $userInfo = $this->usersModel->getUserById($id);
        $this->render('users/profile', ['info' => $userInfo]);
    }
}
```

{% hint style="warning" %}
Important

To create a model, extend the [`BaseModel`](/documents/core/basemodel.md) class and define the `$table`, `$fillable`, and `$guarded` properties as needed. Override any methods as required to meet the specific needs of the model.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.cmsfullform.com/documents/models.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
