Sado ORM Object Documentation
The SadoORM class can be used to create ORM classes and use ORM objects to interact with the database connection instances.To start using ORM objects, begin with including the bootstrap file and then create an ORM class:
// include bootstrap
require_once './lib/Sado/sado.bootstrap.php';
// create a basic ORM class
class User extends SadoORM
{
// nothing needs to be here
}Now in the schema file set the class 'User' for the 'users' table. Or, instead of using the schema file (which is easier and recommended) you can manually define a table in the ORM class: [...]
// create a basic ORM class
class User extends SadoORM
{
// initialize ORM object
protected function __init()
{
// set table name
$this->name('users');
// set primary key field name
$this->key('user_id');
// set remaining fields
$this->field('fullname');
$this->field('email');
$this->field('is_active');
}
}
Now, we can create an User ORM object using our class:
// set instance of User object
$user = new User;
// set some user values
$user->fullname = 'Shay Anderson';
$user->email = 'email@domain.com';
// create a new user
$user->save();Or, we can load a specific user with the user ID: // load user with ID 5:
$user = new User(5);
// change users name
$user->fullname = 'New Name';
// update the users table
$user->save();Deleting a table record is simple: // load user with ID 5
$user = new User(5);
// delete record
$user->destroy();Sometimes it helpful to use the Sado connection instance for manual queries: // add to the user ORM class:
class User extends SadoORM
{
// setup method to get all active users
public function getActiveUsers()
{
// select all active users
$this->getSadoInstance()->select(' SELECT * FROM users WHERE is_active = 1 ');
// return active users
return $this->getSadoInstance()->getRecords();
}
}
// set object
$user = new User;
// set active uers list
$active_users_list = $user->getActiveUsers();
// print active users list
print_r($active_users_list);
If you are using multiple connections in the bootstrap file, you can set an instance ID for an ORM class with this method:
class User extends SadoORM
{
// use the initialization method
protected function __init()
{
// set the connection ID to 2 (by default it uses the first connection and this is not required)
$this->setInstanceId(2);
}
}
