User Tools

Site Tools


tina4:orm

ORM

Save a record using the ORM

The [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping) in Tina4 tries to be as light as possible on coding, the basic form uses the object name to map to the table and assumes the first public variable you declare is the primary key. It is required to extend the ``\Tina4\ORM`` class to make the magic happen.

Examples:

orm-example.php
<?php
 
//we need a class extending the ORM
class User extends \Tina4\ORM { //assumes we have a table user in the database
    public $id; //primary key because it is first
    public $name; //some additional data
}   
 
$user = (new User());
$user->name = "Test Save";
$user->save();
 
 
//We want the table to be made for us
class NewTable extends \Tina4\ORM { 
    //will be created as newtable in the database
    /**
    *  @var id integer auto_increment  
    **/
    public $id; //primary key because it is first
    /**
    *  @var varchar(100) default 'Default Name'
    **/
    public $name; //some additional data
} 
 
 
$newTable = (new NewTable());
$newTable->name = "Test Save";
$user->save();
 
//How about some thing else
 
$newTable = (new NewTable('{"name":"TEST"}'));
$newTable->save();
 
//Or something else
 
$fields = ["name" => "Testing"];
$newTable = (new NewTable($fields));
$newTable->save();
 
//Or something else - request variable should obviously 
//contain fields that match the class declared
$newTable = (new NewTable($_REQUEST));
$newTable->save();

Save Dates

Your Date Format should be set correctly in your index.php file.

From here you can save dates into an ORM object like this:

$article->publishedDate = date($article->DBA->dateFormat." H:i:s");

Any dates that you return from the ORM will follow your localization date format set in index.php I.e. d/m/Y

Map my ORM object to a table with another name

Well we did expect you would ask this question

Example:

orm-example2.php
class User extends \Tina4\ORM { 
    //assumes we have a table user in the database
    public $tableName="my_weird_database_table"; 
    //tableName makes sure this object gets data to and from this table    
    public $id; //primary key because it is first
    public $name; //some additional data
}

Map my ORM field to a database field which doesn't follow the Tina4 pattern

Example:

orm-example3.php
<?php
class OldTournament extends \Tina4\ORM
{
    public $tableName="TABLENAME";
    public $primaryKey="id"; //set for primary key
 
public $fieldMapping = [
    "id" => "ID",
    "code" => "CODE",       
    "name" => "NAME"];
 
    public $ID;
    public $CODE;
    public $NAME;
}
tina4/orm.txt · Last modified: 2021/05/30 22:11 by barco