HasOne association type
CakePHP 2 Comments »A powerful feature in Cake is the relational data association provided by the model definition. There are four types of associations:
- hasOne
- hasMany
- belongsTo
- hasAndbelongsToMany
After we define the association between 2 models Cake will automatically fetch the data between the “glued” models. For example if the Car model is related to the Image model and is using a hasOne association type when we will retrieve the data using findAll for example in a controller there will be retrived both Car and Image records: $this->Car->findAll()
To use this types of relations correctly is indicated to use naming conventions like:
- Foreign Keys: singular-model-name_id. For example, a foreign key in the "images" table pointing back to the Car a given Image belongs to would be named "car_id".
- Tables name should be at plural
- Model names should be singular form of the tables names.
Example of association and querying data with hasOne between two models Car model and Image model in this cases:
Location: app/models/car.php
-
class Car extends AppModel
-
{
-
var $name = 'Car';
-
array('className' => 'Image',
-
'conditions' => '',
-
'order' => '',
-
'dependent' => true,
-
'foreignKey' => 'car_id'
-
)
-
// the hasOne array is what Cake is using to create the association between this 2 models
-
);
-
}
When we will retrieve data using find() or findAll() calls upon Car model we should see our associated Image model data as well.
Recent Comments