Cakephp Classroom image

osdyui
 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15|Last
Lessons:-Models

Creating and Destroying Associations on the Fly
Sometimes it becomes necessary to create and destroy model associations on the fly. This may be for any
number of reasons:
• You want to reduce the amount of associated data fetched, but all your associations are on the first
level of recursion.
• You want to change the way an association is defined in order to sort or filter associated data.
This association creation and destruction is done using the CakePHP model bindModel() and unbindModel()
methods. (There is also a very helpful behavior called “Containable”, please refer to manual section aboutBuilt-in behaviors for more information). Let’s set up a few models so we can see how bindModel() and
unbindModel() work. We’ll start with two models:
class Leader extends AppModel {
public $hasMany = array(
’Follower’ => array(
’className’ => ’Follower’,
’order’ => ’Follower.rank’
)
);
}
class Follower extends AppModel {
public $name = ’Follower’;
}
Now, in the LeadersController, we can use the find() method in the Leader model to fetch a Leader and its
associated followers. As you can see above, the association array in the Leader model defines a “Leader
hasMany Followers” relationship. For demonstration purposes, let’s use unbindModel() to remove that
association in a controller action:
public function some_action() {
// This fetches Leaders, and their associated Followers
$this->Leader->find(’all’);
// Let’s remove the hasMany...
$this->Leader->unbindModel(
array(’hasMany’ => array(’Follower’))
);
// Now using a find function will return
// Leaders, with no Followers
$this->Leader->find(’all’);
// NOTE: unbindModel only affects the very next
// find function. An additional find call will use
// the configured association information.
// We’ve already used find(’all’) after unbindModel(),
// so this will fetch Leaders with associated
// Followers once again...
$this->Leader->find(’all’);
}
Note: Removing or adding associations using bind- and unbindModel() only works for the next find operation
only unless the second parameter has been set to false. If the second parameter has been set to false,
the bind remains in place for the remainder of the request.
Here’s the basic usage pattern for unbindModel():
$this->Model->unbindModel(
array(’associationType’ => array(’associatedModelClassName’))

 
 
 

osdyui

Skills    Cakephp

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)