Chapter 6. Models

Table of Contents

6.1. What is a model?
6.2. Model Functions
6.2.1. User-Defined Functions
6.2.2. Retrieving Your Data
6.2.3. Complex Find Conditions (using arrays)
6.2.4. Saving Your Data
6.2.5. Model Callbacks
6.3. Model Variables
6.4. Associations
6.4.1. Introduction
6.4.2. Defining and Querying with hasOne
6.4.3. Defining and Querying with belongsTo
6.4.4. Defining and Querying with hasMany
6.4.5. Defining and Querying with hasAndBelongsToMany
6.4.6. Saving Related Model Data
6.4.7. Saving hasAndBelongsToMany Relations
6.4.8. Changing Associations on the Fly using bindModel() and unbindModel()

6.1. What is a model?

What does it do? It separates domain logic from the presentation, isolating application logic.

A model is generally an access point to the database, and more specifically, to a certain table in the database. By default, each model uses the table who's name is plural of its own, i.e. a 'User' model uses the 'users' table. Models can also contain data validation rules, association information, and methods specific to the table it uses. Here's what a simple User model might look like in Cake:

Example 6.1. Example User Model, saved in /app/models/user.php

<?php

//AppModel gives you all of Cake's Model functionality

class User extends AppModel
{
    // Its always good practice to include this variable.
    var $name = 'User';

    // This is used for validation, see Chapter "Data Validation".
    var $validate = array();

    // You can also define associations.
    // See section 6.3 for more information.

    var $hasMany = array('Image' =>
                   array('className' => 'Image')
                   );

    // You can also include your own functions:
    function makeInactive($uid)
    {
        //Put your own logic here...
    }
}

?>