Fuel Documentation

Models

What are models?

Whenever data needs to be retrieved, manipulated or deleted this should always be done by a model. A Model is a representation of some kind of data and has the methods to change them. For example: you never put SQL queries in a Controller, those are put in the Model and the Controller will call upon the Model to execute the queries. This way if your database changes you won't need to change all your Controllers but just the Model that acts upon it.

How are Models used?

In Fuel a Model is essentially just a Class like any other. They do nothing more than a library, but the Model_ prefix helps to differentiate it from other classes. To do something useful with a Model you will need to use other classes.

Writing your own models

While models can be used with any type of data storage we'll focus here on usage with SQL because that's the most common usage. Almost always your models will have at least all CRUD methods: create, read, update, delete (or variations on those). In Fuel your models don't need to extend anything by default, though you can of course create your own base model or use Fuel's Orm package.

Writing SQL Queries

You can use the DB class to build queries with native SQL like so:

DB::query('SELECT * FROM users WHERE id = 5');

Using the Query Builder

When it comes to escaping data, working with data in arrays or making an application portable over multiple database engines, you might find native SQL to be rather cumbersome. Using the Query Builder methods in the DB Class you can abstract writing native SQL:

DB::select('title, content')->from('articles')->execute()->get();

See more about native SQL queries and using the Query Builder in the DB class documentation.

Using the Orm to create models

One possible way of creating models is by using the Orm Package, which adds a lot of functionality out-of-the-box to your models. There's an example of its usage below.

// find all articles
$entry = Model_Article::find('all');

// find all articles from category 1 order descending by date
$entry = Model_Article::find('last', array(
    'where' => array('category_id', 1),
    'order_by' => array('date', 'desc')
));

See more about working with ORM in the Orm Package documentation.