2011-01-14 01:49:56 +11:00
# Basic Usage
## Load a new model instance
2011-05-16 22:47:16 +10:00
To create a new `Model_User` instance, you can do one of two things:
2011-01-14 01:49:56 +11:00
$user = ORM::factory('user');
2011-05-16 22:47:16 +10:00
// Or
2011-01-14 01:49:56 +11:00
$user = new Model_User();
## Inserting
To insert a new record into the database, create a new instance of the model:
$user = ORM::factory('user');
Then, assign values for each of the properties;
$user->first_name = 'Trent';
$user->last_name = 'Reznor';
$user->city = 'Mercer';
$user->state = 'PA';
Insert the new record into the database by running [ORM::save]:
$user->save();
[ORM::save] checks to see if a value is set for the primary key (`id` by default). If the primary key is set, then ORM will execute an `UPDATE` otherwise it will execute an `INSERT` .
2011-05-16 22:47:16 +10:00
## Finding an object
2011-01-14 01:49:56 +11:00
2011-05-16 22:47:16 +10:00
To find an object you can call the [ORM::find] method or pass the id into the ORM constructor:
2011-01-14 01:49:56 +11:00
2011-05-16 22:47:16 +10:00
// Find user with ID 20
$user = ORM::factory('user')
->where('id', '=', 20)
->find();
// Or
2011-01-14 01:49:56 +11:00
$user = ORM::factory('user', 20);
## Check that ORM loaded a record
2011-05-16 22:47:16 +10:00
Use the [ORM::loaded] method to check that ORM successfully loaded a record.
2011-01-14 01:49:56 +11:00
if ($user->loaded())
{
2011-05-16 22:47:16 +10:00
// Load was successful
2011-01-14 01:49:56 +11:00
}
else
{
2011-05-16 22:47:16 +10:00
// Error
2011-01-14 01:49:56 +11:00
}
## Updating and Saving
Once an ORM model has been loaded, you can modify a model's properties like this:
$user->first_name = "Trent";
$user->last_name = "Reznor";
And if you want to save the changes you just made back to the database, just run a `save()` call like this:
$user->save();
## Deleting
2011-05-16 22:47:16 +10:00
To delete an object, you can call the [ORM::delete] method on a loaded ORM model.
2011-01-14 01:49:56 +11:00
2011-05-16 22:47:16 +10:00
$user = ORM::factory('user', 20);
2011-01-14 01:49:56 +11:00
$user->delete();