All models in Rack applications extend from the abstract Model
class, defined in include/models/Model.class.php
. This class provides a basic implementation for CRUD (create, read, update, and delete) functionality for a single database table. It utalizes the PDO
prepared statements to construct queries to help preventing SQL injections.
A Model
object should never be manually created, as Rack provide a function get_model($name)
in include/init.php
that creates an instance of a Model
object for you when need it. The following snippet demonstrates its use:
<PHP> $model = get_model('Registration'); $registrations = $model→get(); </PHP>
Basic queries can be executed using the functions get
, create
, update
and delete
or their by_id
counterparts. The create
and update
functions accept a list with 'fieldname'=>'value'
pairs that should be used to modify the database.
The get
, update
and delete
functions also accept an array with filter conditions. These conditions will be appended to the query and multiple conditions will be joined with AND
. In this array, filter conditions should be specified as 'fieldname__function' => $value
.
Supported comparison functions are:
=
) another value.<>
) another value.<
) another value.⇐
) another value.>
) another value.>=
) another value.LIKE '%value%'
). Note that %
and _
will not be automatically escaped.NULL
(if 'field__isnull'=>true
) or not NULL
(if 'field__isnull'=>false
).
If the comparison function is omitted ('field' => $value
), the default of eq is used.
The get
function also supports custom ordering by passing a list of field names. Descending ordering can be achieved by adding a minus in front of the field name. The following example will order first by study and then by birthdate in descending ordering: ['study', '-birthdate']
.
__construct($db, $table=null)
: The variable $db
is a PDO object. This value will be set by get_model
. $table
is the name of the table as it's stored in the database.protected query($query, array $input_parameters=[])
Expects a query and input parameters that that can be used for PDO prepared statements.protected query_first($query, array $input_parameters=[])
Same as query
, but returns only the first result.get(array $conditions=[], array $order=[], $get_first=false)
get_by_id($id, $field='id')
create(array $values)
Returns inserted ID.update(array $data, array $conditions=[])
Use with caution!update_by_id($id, array $data, $field='id')
delete(array $conditions)
Use with caution!delete_by_id($id, $field='id')