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:
php init Models <model_name>
// Example: php init models UsersThis creates UsersModel.php inside application/Model/.
Accessing Model
<?php
use App\Models\UsersModel;
$usersModel = new UsersModel();Configuration
To switch between database drivers, update the db_driver setting in application/Config/Config.php
Example Usage
List of Common Methods in a Model (Example in UsersModel):
Model Configuration and Schema
_schema(): Defines the database schema for theuserstable, specifying columns, data types, and constraints.
Retrieving User Data
getUsers(): Retrieves a list of all users from theuserstable, 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 onID.getUserByIdField($fields, $id): Retrieves specific fields of a user based onID.getUserByUsername($username): Finds a user based onusername.getUserByEmail($email): Finds a user based onemail.
Managing User Data (Add, Update, Delete)
addUser($data): Adds a new user to theuserstable.updateUser($id, $data): Updates user information based onID.deleteUser($id): Deletes a user from the system based onID.
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 theirID, if valid location data exists.
Model in Controller
Important
To create a model, extend the BaseModel class and define the $table, $fillable, and $guarded properties as needed. Override any methods as required to meet the specific needs of the model.
Last updated
Was this helpful?