3. Model - TerminusStudio/ezDB GitHub Wiki
ezDB Models can be used to make the library function similar to an ORM.
The ORM in this library is lightweight and focuses on providing basic functionalities. If you require more functions you can easily extend the Model class .
Defining Models
Models can be defined by extending the Model
class. Each table in your database should have a corresponding Model class (except for many to many relationship tables).
Example model for a table named test
.
<?php
namespace App\Models;
use TS\ezDB\Models\Model;
class TestModel extends Model
{
}
There are a few properties that can be overridden in model classes.
Table
The table property should contain the table name that the model. It is recommended to set the table name for the model even though ezDb automatically generates a snake case table name.
<?php
namespace App\Models;
use TS\ezDB\Models\Model;
class TestModel extends Model
{
/**
* @var string The table name
*/
protected $table = 'test';
}
Primary Key
By default ezDB assumes that all tables have a primary key called 'id'. This can be changed by defining the $primaryKey
property in the model.
<?php
namespace App\Models;
use TS\ezDB\Models\Model;
class TestModel extends Model
{
/**
* @var string The primary key of the table
*/
protected $primaryKey = 'test_id';
}
You can also set the attribute to false
if the table does not have a primary key. If the primary key is false, functions such as find()
and save()
will not work.
Currently there is no support for composite primary keys. If your table uses a composite primary keys then avoid using save()
method.
Timestamps
ezDb supports managing created_at
and updated_at
timestamps by default. You can disable timestamps for models by setting the $timestamp
property.
<?php
class TestModel extends Model
{
/**
* @var bool Timestamps will automatically be managed. Create two extra columns: created_at and updated_at
* Set this to false to disable timestamps
*/
protected $timestamps = false;
}
The default column names is 'created_at' and 'updated_at'. The type of the columns needs to be timestamp
, but any type that accepts Y-m-d H:i:s
is allowed (has not been tested on any other type).
To change the default column names, define the following const property in your Model,
<?php
class TestModel extends Model
{
/**
* Column name for created_at
*/
public const CREATED_AT = 'created_at';
/**
* Column name for updated_at
*/
public const UPDATED_AT = 'updated_at';
}