Binding model associations dynamically with CakePHP :
In the Model file :
var $bindings = array(
‘belongsTo’ => array(
‘User’ => array(
‘className’ => ‘User’,
‘foreignKey’ => ‘user_id’,
‘dependent’ => false,
‘fields’ => ”,
‘order’ => ”
)
),
‘hasMany’ => array(
‘Message’ => array(
‘className’ => ‘Message’,
‘foreignKey’ => ‘classified_id’,
‘dependent’ => false
)
)
);
var $bindings = array(
‘belongsTo’ => array(
‘User’ => array(
‘className’ => ‘User’,
‘foreignKey’ => ‘user_id’,
‘dependent’ => false,
‘fields’ => ”,
‘order’ => ”
)
),
‘hasMany’ => array(
‘Message’ => array(
‘className’ => ‘Message’,
‘foreignKey’ => ‘classified_id’,
‘dependent’ => false
)
)
);
In the app_model.php :
function expects($array) {
$this->bindModel(array($array['type'] => array($array['model']=>$this->bindings[$array['type']][$array['model']])));
}
And then call it when needed in a controller :
$this->Classified->expects(array(’type’=>’belongsTo’,'model’=>’User’));
$this->Classified->expects(array(’type’=>’hasMany’,'model’=>’Message’));
It works !
