CakePhp Association With Example
CakePhp Association Example
CakePhp provides a very powerfull mechanism to handle relation between models ( i.e foreign key relationship between database tables ) by itself with the call of just one function.
The four association types in CakePHP are:
hasOne, hasMany, belongsTo, and hasAndBelongsToMany (HABTM).
Here I am giving expamle for hasOne association in CakePhp.
There will be two models : –
- Seller – This model refer the basic seller info. and link with sellers table in database and have onetone relationship with the SellerProperyInfo.
- SellerProperyInfo – This model refer the seller property info and link with Seller model via foriegn key relationship and all these associations are defined in the model classes.
Linking Model Classes : –
class Seller extends AppModel { public $hasOne = array( 'SellerPropertyInfo' =>array( 'className' => 'SellerPropertyInfo', 'foreignKey' => 'user_id', 'dependent' => true ) ); }
class SellerPropertyInfo extends AppModel { public $belongsTo = array( 'Seller'=> array( 'className' => 'Seller', 'foreignKey' => 'user_id', 'dependent' => true ) ); }
We are done with the linking model classes with hasOne relation now we have to build a form so that user can enter both seller and seller property info.
After making form we just have to make a single function call and it will save the data in both the tables according to the relation defined in model classes. Below is the function call in the controller.
. . $this->Seller->saveAssociated($this->request->data); . .
For more information go to Cake Docs