Adding bindings on the fly

This recipe shows how to set up new bindings right before a find operation, including bindings that are automatically removed after the operation is executed, and bindings that are permanently added.

Getting ready

We need some sample models and data to work with. Follow the Getting ready section of the recipe, Modifying binding parameters for a find.

How to do it...

If we want to obtain the latest published Article when we are fetching a User, we could add a permanent binding to the User model. However, if we want to do this on a need-by-need basis, it is smarter to add the binding before the find operation that needs it, thus avoiding the unneeded overhead for other operations.

We can add the needed binding and then issue the find operation:

$this->User->bindModel(array(
'hasOne' => array(
'LastArticle' => array(
'className' => 'Article',
'conditions' => array(
'LastArticle.published' => 1
),
'order' => array(
'LastArticle.created' => 'desc',
'LastArticle.id' => 'desc'
)
)
)
));
$user = $this->User->find('first', array(
'conditions' => array(
'User.id' => 1
),
'contain' => array(
'LastArticle' => array('fields' => array('title'))
)
));

The preceding code would give us the following data structure:

array(
'User' => array(
'id' => '1',
'name' => 'John Doe',
'email' => '[email protected]',
),
'LastArticle' => array(
'title' => 'John's Post 4'
)
)

If we want to make the binding permanent until the request ends, but without adding the binding to the User model, we simply add the value false as a second parameter to the bindModel() call (this is needed if the operation is a paginate () call, as this call will issue two find operations):

$this->User->bindModel(array(
'hasOne' => array(
'LastArticle' => array(
'className' => 'Article',
'conditions' => array(
'LastArticle.published' => 1
),
'order' => array(
'LastArticle.created' => 'desc',
'LastArticle.id' => 'desc'
)
)
)
), false);

How it works...

When you issue a bindModel() call, CakePHP will add the binding as if you specified it on the model itself. If you did not set the second parameter to the method as false, that binding will be automatically removed after the find operation is completed. If you did set it in order to avoid the reset, then it will be kept until the script instance of your application is finished.

The format to specify bindings through bindModel() is an array, indexed by the binding type (one of belongsTo, hasOne, hasMany, and hasAndBelongsToMany), whose value for each binding type is an array of associations.

You define each association (as you would normally do) in the model, indexing it by association name (if it is different than the model's name it is pointing to or if you have binding parameters to define), or, optionally, simply referring to the related model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.235.23