Models

SigmaPHP framework provides an ORM that allows you to interact with and control your database data without writing SQL queries. Instead, you work with plain PHP objects. The ORM maps your database table columns to model properties, allowing you to read, update, and manipulate data using simple object-oriented syntax.

Creating Models

For convenience, the SigmaPHP CLI tool provides a command to generate a new model automatically.


./bin/sigma-cli create:model Product
    

The command above will create new Model Product inside the app/Models directory.


<?php

namespace App\Models;

use SigmaPHP\Core\Models\BaseModel;

class Product extends BaseModel
{
    // The ORM will automatically determine the table name and columns
}
    

This command will also generate a corresponding migration file to create the database table associated with the model. Both the model and the migration file will be placed in their default directories.

To customize these paths, open the database.php configuration file and update the following settings:


 /**
   * Default path for migration files.
   */
'path_to_migrations' => env('PATH_TO_MIGRATIONS', '/database/migrations'),

...

/**
  * Default path for migrations files.
  */
'path_to_models' => env('PATH_TO_MODELS', '/app/Models'),
    

By default, the ORM automatically determines the table name and retrieves its fields. It assumes the table name is the plural form of the model class name. For example, a model named Product will correspond to a table named products.

The default primary key is id. If you need to customize the table name, primary key, or fields, you can override the corresponding properties in your model.

Additionally, if you want to use UUIDv4 as the primary key, you can enable this by setting the $uuid property to true. Make sure the primary key column in your migration uses a compatible data type such as CHAR, BINARY, or the custom uuid type.


<?php

namespace App\Models;

use SigmaPHP\Core\Models\BaseModel;

class User extends BaseModel
{
    protected $table = 'users_table';

    protected $primary = 'user_id';

    protected $uuid = true;

    protected $fields = ['user_id', 'name', 'age'];
```

} 

Working with Models

There are two main ways to create a new instance of a model: using the create() method or the save() method.

Using the create Method

The create() method accepts an array of data and returns a new model instance.


<?php

$userModel = new User();

$newUser = $userModel->create([
'name' => 'John Doe',
'age' => 35
]);

echo $newUser->name;
    

Using the save Method

The save() method can be used for both creating and updating models. In this case, you assign the field values manually before saving.


<?php

$newUser = new User();

$newUser->name = 'John Doe';
$newUser->age = 35;

$newUser->save();

echo $newUser->name;
    

Retrieve Models Data

The ORM provides several methods to retrieve data from the database.


<?php

// fetch single model
$user = $userModel->first();

// fetch all models
$users = $userModel->all();

// count all models
$usersCount = $userModel->count();

// find by primary key
$user = $userModel->find(5);

// find by field
$user = $userModel->findBy('age', 35); 

You can also build more advanced queries using conditional methods.


<?php

// basic where
$user = $userModel
    ->where('email', 'like', '%@testing.com')
    ->first();

// and where
$usersCount = $userModel
    ->where('age', '>=', 35)
    ->andWhere('gender', '=', 'male')
    ->count();

// or where
$users = $userModel
    ->where('name', 'like', '%test%')
    ->orWhere('role', 'in', '("super admin", "admin")')
    ->all();

// search by relation
$user = $userModel
    ->whereHas('posts', 'published_at', 'is', 'null')
    ->first();

// check if relation exists
$users = $userModel
    ->whereHas('posts')
    ->all();
    

Update Model

To update a model, retrieve it first, modify its properties, then call the save() method.


<?php

$user = $userModel->find(15);

$user->name = 'Mohamed';

$user->save();
    

Delete Model

Deleting a model is straightforward. Simply retrieve the model and call the delete() method.


<?php

$user = $userModel->find(15);

$user->delete();
    

Soft Delete

The ORM supports soft deletion, which allows records to be marked as deleted without being permanently removed from the database.

To enable this feature, your table must contain a deleted_at column. Which you can add using migrations:


    $this->createTable(
        'products',
        [
            ['name' => 'id', 'type' => 'uuid'],
            ...
            ['name' => 'soft_delete'],
            ['name' => 'timestamps']
        ]
    );
            

You can then enable soft deletes by using the SoftDelete trait in your model.


<?php

namespace App\Models;

use SigmaPHP\Core\Models\BaseModel;
use SigmaPHP\DB\Traits\SoftDelete;

class Product extends BaseModel
{
use SoftDelete;
}
    

After enabling the trait, calling delete() will update the deleted_at field instead of permanently removing the record.


<?php

$product = $productModel->find(7);

$product->delete();
    

The SoftDelete trait also provides several additional helper methods.


<?php

// include soft deleted models
$allProducts = $productModel->withTrashed()->all();

// check if a model is soft deleted
$isDeleted = $product->isTrashed();

// restore a soft deleted model
$product->restore();

// fetch only soft deleted models
$onlyTrashedProducts = $productModel->onlyTrashed()->all();

// permanently delete a soft deleted model by
// setting $forceHardDelete parameter to true
$product->delete(true);
    

You can also configure the model to always include soft-deleted records in queries by setting the $fetchTrashed property to true.


<?php

namespace App\Models;

use SigmaPHP\Core\Models\BaseModel;
use SigmaPHP\DB\Traits\SoftDelete;

class Product extends BaseModel
{
    use SoftDelete;

    protected $fetchTrashed = true;

    ...
}
    
Back to top