Association is basically linking two models of the database.
It is very useful.
After applying association you don't need to join the tables from the controller and fetch the data of another model from the controller.
The four types of association are-
1. hasOne- It's one to one association. Like a user has only one profile. each user entry will point towards one profile entry.
2.hasMany- It's one to many association. Like a user has many departments. each user will point toward many departments.
3. belongsTo- It's many to one association. Like multiple users can have a single office building. Multiple user will point towards a single office building.
4. hasAndBelongsToMany - It's many to many association. Like multiple users have multiple departments. many users will point toward many departments.
You can simply use them in your model where you want to apply association.
Like if you want to join user with department and department with user.
You can go to user model and define.
class User extends AppModel {
$hasMany = ("departments");
or if you want to give some more functionalities you can use array.
class User extends AppModel {
$hasMany = array("departments", array("
'conditions' => array('Department.store' => '1'),
'order' => 'Department.created DESC'));
This makes the fetching of data really easy from one controller only.
But in case you want to find the data of only the user you have to use recursive -1 in your controller so it can fetch the data of that particular model only.
0 Comment(s)