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
100644 48 lines (31 sloc) 1.575 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
=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 (c) 2008 Michal Szajbe (http://codetunes.com) and netguru (http://netguru.pl), released under the MIT license