Category Covered

CakePHP association models

CakePHP association or relationship between models

 

Relationship    Association Type       Example

one to one      hasOne                 A user has one profile.

one to many     hasMany                A user can have multiple recipes.

many to one     belongsTo              Many recipes belong to a user.

many to many    hasAndBelongsToMany    Recipes have, and belong to many tags.

 
CakePHP Has One relationship/association

hasOne: the other model contains the foreign key.

Relation
Schema

Apple hasOne Banana

bananas.apple_id

User hasOne Profile

profiles.user_id

Doctor hasOne Mentor

mentors.doctor_id
 
class User extends AppModel {

    public $hasOne = array(

        'Profile' => array(

            'className'    => 'Profile',
            'conditions'   => array('Profile.published' => '1'),
            'dependent'    => true
        )
    );
}
 
CakePHP Has Many relationship/association
 

hasMany: the other model contains the foreign key.

Relation
Schema

User hasMany Comment

Comment.user_id

Cake hasMany Virtue

Virtue.cake_id

Product hasMany Option

Option.product_id
 
class User extends AppModel {

    public $hasMany = array(

        'MyRecipe' => array(

            'className' => 'Recipe',

        )
    );
   
}
 
 
 
CakePHP Belongs To relationship/association
 

belongsTo: the current model contains the foreign key.

Relation
Schema

Banana belongsTo Apple

bananas.apple_id

Profile belongsTo User

profiles.user_id
Mentor belongsTo Doctor
mentors.doctor_id
 
class Profile extends AppModel {

    public $belongsTo = array(

        'User' => array(

            'className'    => 'User',
            'foreignKey'   => 'user_id'
        )
    );
}
 
CakePHP Has And Belongs To Many relationship/association
class User extends AppModel {

    public $hasAndBelongsToMany = array(

        'MemberOf' => array(

            'className' => 'Group',

        )
    );
}

 

 

 

More details from

 

Next Step: CakePHP recursive tutorial