<< Back
Model Association in Cake PHP
Model Association in Cake PHP
Model Association in Cake PHP
There have four types of association in CakePHP are: hasOne, hasMany, belongsTo, and hasAndBelongsToMany (HABTM)
Has One:
It is one to one relationship. For Ex. A user has one profile.
class User extends AppModel {
public $hasOne = array(
'Profile' => array(
'className' => 'Profile',
'foreignKey' => 'user_id',
'dependent' => true
)
);
}
Has Many:
It is one to many relationship. For Ex. A students can have multiple subjects.
class Student extends AppModel {
public $hasMany = array(
'Subject' => array(
'className' => 'Subject',
'foreignKey' => 'student_id',
'dependent' => true
)
);
}
Belongs To:
It is many to one relationship. For Ex. Many subjects belong to a student.
class Subject extends AppModel {
public $belongsTo = array(
'Student' => array(
'className' => 'Student',
'foreignKey' => 'student_id'
)
);
}
Has and Belongs To Many:
It is many to many relationship. For Ex. Subjects have, and belong to many chapters.
class Subject extends AppModel {
public $hasMany = array(
'Chapter' => array(
'className' => 'Chapter',
)
);
public $hasAndBelongsToMany = array(
'ChapterName' => array(
'className' => 'ChapterName',
'joinTable' => 'Chapter',
'foreignKey' => 'student_id',
'associationForeignKey' => 'chapter_id',
'fields'=>''
)
);
}
Published: 30th April 2020 by Gabriel Kolbe
