Cakephp hasMany and belongsTo with example

CakePHP offers excellent way for associations for linking models. There are 4 types of relationship in CakePHP which are as below.

1) hasone is used for One to one relationship.
2) hasMany is used for one to many relationships.
3) belongsTo is used for many to one relationship.
4) hasAndBelongsToMany is used for many to many relationship.

Cakephp Associations Linking Models  Relationship Types with example

Cakephp Associations Linking Models Relationship Types with example

Have a look on the example and explanation of hasMany and belongsTo relationship.

Example

This example is useful to understand Category and Product relationship in cakephp.

Category table have two fields “id” and “CategoryName”.

Product table have three fields “id”, “category_id” and “ProductName”. You can add as many fields as you want in product table but I took only 3 to explain the relationship with category.

 
class Category extends AppModel {
    public $order = "CategoryName";
 
    public $hasMany = array(
        'Product' => array(
            'className' => 'Product',
            'foreignKey' => 'category _id',
            'dependent' => true
        )
    );
}

In the Category model class, each category have either one or more than one products. when you are doing association like this than you have to use “hadMany” relationship in CakePHP. I define that “category_id” is a foreignkey in product table. Example of CakePHP “hasMany” relationship type.

 
class Product extends AppModel {
    public $order = "ProductName";        
 
    public $belongsTo = array(
            'Category' => array(
                'className' => ' Category ',
                'foreignKey' => 'category_id'
            )
        );
}

In the Product model class, each product belongs to any one category. I define that “category_id” is a foreignkey in product table. Example of CakePHP “belongsTo” relationship type.

Many developer confuse here and try to use CakePHP “hasOne” relationship type in product model class which will not work at all. I hope that, this example is useful to clear your confusion about the CakePHP relationship types.