New Feature: bindModel/unbindModel
This feature allows you to bind or turn off associations on the fly, and will be available in the next release (RC6?) of CakePHP.
Let us start with an unbindModel example. We have three models: User, Project and Supportrequest. A user has many projects and many support requests. If we do
debug($this->User->findAll());
the output would be something like:
Array
(
[0] => Array
(
[User] => Array
(
[id] => 1
[firstname] => Daniel
[lastname] => Hofstetter
)
[Project] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[name] => project A
)
)
[Supportrequest] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[comment] => a support request
)
[1] => Array
(
[id] => 2
[user_id] => 1
[comment] => another support request
)
)
)
)
Ok, but what if we are only interested in the users and the projects? Well, we could simply ignore the support requests. Or we could turn off the association to the support requests with unbindModel:
$this->User->unbindModel(array('hasMany' => array('Supportrequest')));
debug($this->User->findAll());
That gives us the following output:
Array
(
[0] => Array
(
[User] => Array
(
[id] => 1
[firstname] => Daniel
[lastname] => Hofstetter
)
[Project] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[name] => project A
)
)
)
Notice: The associations are reset after each call to a find function.
Ok, that was the unbindModel example. Let us go to the bindModel example. That example will be a little bit artificial as I do not see a real use case for bindModel at the moment. Maybe you know one? Ok, we have two Models: User and Supportrequest. The model do not have any associations. If we do
debug($this->User->findAll());
we get the following output:
Array
(
[0] => Array
(
[User] => Array
(
[id] => 1
[firstname] => Daniel
[lastname] => Hofstetter
)
)
)
For some reason we want to have a temporary “hasMany” association between user and support request. We define it in the following way using the usual association syntax:
$this->User->bindModel(array('hasMany' => array('Supportrequest' =>
array('foreignKey' => 'user_id'))));
debug($this->User->findAll());
And that is the output:
Array
(
[0] => Array
(
[User] => Array
(
[id] => 1
[firstname] => Daniel
[lastname] => Hofstetter
)
[Supportrequest] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[comment] => a support request
)
[1] => Array
(
[id] => 2
[user_id] => 1
[comment] => another support request
)
)
)
)
That’s it :) (original)
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home