Working with Kohana’s ORM isn’t really something you can find definitive information and usage examples on, which is a shame, because Kohana has a surprisingly decent in-built ORM you can use in your projects.
In this tutorial, I will touch on enabling the ORM module, creating a model that works with the ORM and performing a bunch of different queries. This article will assume you are using Kohana 3.3 and will be updated for future versions if anything changes.
Relationships will not be touched upon in this post, that will be a completely separate post that will be up shortly.
Enabling the ORM Module
Modules are enabled in your application/bootstrap.php file. Down the bottom of the file you should see an array of various modules, the userguide, auth, database and of course ORM module. Simply uncommenting the line for the ORM module is all you need to do. You of course also need to have the database module enabled as well, but it is assumed you are more than able to at least achieve this part on your own.
Create an ORM friendly model
The general rule of thumb is to create a model file for each table in your database. For this example we are assuming you have a table in your database called, “users”. We will be creating a user model to interact with this table.
Create a new file in application/classes/Model called “user.php” so your path to the file should be: application/classes/Model/user.php. Copy and paste the following code into the model and save it.
[code]
<?php defined(‘SYSPATH’) or die(‘No direct script access.’); ?>
class Model_User extends ORM
{
}
[/code]
That’s all we need to do basic CRUD (Create, Read, Update, Delete) operations on our users table.
Kohana Basic ORM CRUD Operations
We are now going to perform some basic operations on our users table. For this example we will use the Welcome controller located in application/classes/Controller/Welcome.php and write our code inside of action_index to save time and further lessons on how controllers work.
Create – Inserting a new entry into the users table
We have to first instantiate our user model. There are two ways we can do this, one is using a direct approach utilising the new keyboard and the other is using the ORM factory method. For the sake of this example and all further examples of database interaction, we will use the factory method.
[code]
$user = ORM::factory(“User”);
$user->username = “admin”;
$user->first_name = “Admini”;
$user->last_name = “Strator”;
$user->location = “Australia”;
try
{
// Try and save
$user->save();
}
catch (ORM_Validation_Exception $e)
{
// Catch errors, make dollars
$errors = $e->errors(‘User’);
}
[/code]
The above code will perform an insert into our database, but if we were to set a primary ID value, it would perform an update instead. Please note the above will not check if the inserted value already exists or not, it will keep creating new rows as the primary key auto increments making each insert unique.
Read – Query the database for one or more rows
Unless you’re building a Twitter or Facebook clone, there’s a good chance your app will primarily be read heavy. The Kohana ORM supports all of the usual ways of interfacing with a database as well as relationships (one-to-one, one-to-many, many-to-many) and other cool database things.
Simple database query by ID retrieving one row
[code]
/**
* Find a user with the ID of 10 (the id field is our primary key)
* We can actually do the following query a couple of different ways, this is easiest when
* querying by primary key.
*
* The following is the same as: ORM::factory(“User”)->where(“id”, “=”, 10)->find()
*
*/
$user = ORM::Factory(“User”, 10);
// If a user was found with that ID
if ($user->loaded())
{
}
[/code]
Simple database query, get all banned users (multiple rows)
[code]
$user = ORM::Factory(“User”);
$user->where(“status”, “=”, “banned”);
$user->find_all();
if ($user->loaded())
{
// Database results were found, we have banned users
}
else
{
// No database results were found
}
[/code]
Update – Update a pre-existing database row
Updating a pre-existing database row is something you would commonly do when editing a user for example. Maybe changing a username or changing their status to banned.
[code]
// Lets get user with ID of 10 again
$user = ORM::Factory(“User”, 10);
// User exists
if ($user->loaded())
{
// User number 10 wants to be renamed Michael Jordan
$user->first_name = “Michael”;
$user->last_name = “Jordan”;
try
{
$user->save();
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors(‘User’);
}
}
[/code]
Delete – Remove a row from the database
Deleting a row deletes it for good and Kohana’s ORM makes it easy.
[code]
// Lets get user with ID of 10 again
$user = ORM::Factory(“User”, 10);
// User exists (but not for long)
if ($user->loaded())
{
try
{
// User number ten is too fussy, lets delete him.
$user->delete();
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors(‘User’);
}
}
[/code]
What if I do not want to update my record based on ID? How do I update then?