public
Description: Behavior for CakePHP that allows use of named scopes with model's find() method.
Homepage: http://codetunes.com/2008/09/05/named-scope-in-cakephp/
Clone URL: git://github.com/netguru/namedscopebehavior.git
commit  71edd461a2a3b0edb0908200062345fc32b81f19
tree    1775ee19a8d4516b2f113e4d5d56ced6b2bfe2db
parent  6a3598bd390c7baa50441007e0603498ef7214a2
name age message
file MIT-LICENSE Sun Aug 31 13:57:17 -0700 2008 copyrights update [netguru]
file README Tue Sep 16 14:24:50 -0700 2008 param name changed to 'scopes' due to confict w... [netguru]
file README.rdoc Tue Sep 16 14:24:50 -0700 2008 param name changed to 'scopes' due to confict w... [netguru]
file named_scope.php Loading commit data...
README.rdoc

NamedScopeBehavior

This is a behavior for CakePHP that allows use of named scopes with model’s find() method. What it does it translating defined scopes to conditions before extecuting find query.

Installation

Download and place named_scope.php file in app/models/behaviors folder of your CakePHP application.

Usage

Example of User model:

$actsAs = array(

  'NamedScope' => array(
    'activated' => array('User.activated' => 1),
    'online' => array('date_add(User.last_activity, interval 5 minute) > now()')
  )

);

Then in your controller (or anywhere else) you can do:

$this->User->find(‘all’, array(‘scopes’ => array(‘activated’)));

which is an equivalent to:

$this->User->find(‘all’, array(‘conditions’ => array(‘User.activated’ => 1)));

You can use many scopes at once and mix them with usually defined conditions:

$this->User->find(‘all’, array(‘condtions’ => array(‘User.admin’ => 1), ‘scopes’ => array(‘activated’, ‘online’)))

If you have associated models (hasOne or belongsTo) and they have named scopes defined you can use them all in one find query: $this->User->find(‘all’, array(‘scopes’ => (‘activated’, ‘Group.admins’))) // assuming that User belongsTo Group and Group model has ‘admins’ named scope defined.

Scopes works also with pagination (in your controller):

$paginate = array(

  'User' => array(
    'order' => 'created ASC',
    'limit' => 20,
    'scopes' => array('online', 'activated')
  )

)

Copyright

Copyright © 2008 Michal Szajbe (codetunes.com) and netguru (netguru.pl), released under the MIT license