netguru / namedscopebehavior
- Source
- Commits
- Network (1)
- Issues (0)
- Downloads (0)
- Wiki (1)
- Graphs
-
Tree:
623a7a4
namedscopebehavior / README
| 378af411 » | netguru | 2008-08-31 | 1 | =NamedScopeBehavior | |
| 2 | |||||
| 3 | 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. | ||||
| 4 | |||||
| 5 | ==Installation | ||||
| 6 | |||||
| 7 | Download and place named_scope.php file in app/models/behaviors folder of your CakePHP application. | ||||
| 8 | |||||
| 9 | ==Usage | ||||
| 10 | |||||
| 11 | Example of User model: | ||||
| 12 | |||||
| 13 | $actsAs = array( | ||||
| 14 | 'NamedScope' => array( | ||||
| 15 | 'activated' => array('User.activated' => 1), | ||||
| 16 | 'online' => array('date_add(User.last_activity, interval 5 minute) > now()') | ||||
| 17 | ) | ||||
| 18 | ); | ||||
| 19 | |||||
| 20 | Then in your controller (or anywhere else) you can do: | ||||
| 21 | |||||
| 1da50803 » | netguru | 2008-09-16 | 22 | $this->User->find('all', array('scopes' => array('activated'))); | |
| 378af411 » | netguru | 2008-08-31 | 23 | ||
| 24 | which is an equivalent to: | ||||
| 25 | |||||
| 26 | $this->User->find('all', array('conditions' => array('User.activated' => 1))); | ||||
| 27 | |||||
| 28 | You can use many scopes at once and mix them with usually defined conditions: | ||||
| 29 | |||||
| 1da50803 » | netguru | 2008-09-16 | 30 | $this->User->find('all', array('condtions' => array('User.admin' => 1), 'scopes' => array('activated', 'online'))) | |
| 378af411 » | netguru | 2008-08-31 | 31 | ||
| bf221a60 » | netguru | 2008-09-14 | 32 | If you have associated models (hasOne or belongsTo) and they have named scopes defined you can use them all in one find query: | |
| 1da50803 » | netguru | 2008-09-16 | 33 | $this->User->find('all', array('scopes' => ('activated', 'Group.admins'))) | |
| bf221a60 » | netguru | 2008-09-14 | 34 | // assuming that User belongsTo Group and Group model has 'admins' named scope defined. | |
| 35 | |||||
| 1da50803 » | netguru | 2008-09-16 | 36 | Scopes works also with pagination (in your controller): | |
| 378af411 » | netguru | 2008-08-31 | 37 | ||
| 38 | $paginate = array( | ||||
| 39 | 'User' => array( | ||||
| 40 | 'order' => 'created ASC', | ||||
| 41 | 'limit' => 20, | ||||
| 1da50803 » | netguru | 2008-09-16 | 42 | 'scopes' => array('online', 'activated') | |
| 378af411 » | netguru | 2008-08-31 | 43 | ) | |
| 44 | ) | ||||
| 45 | |||||
| 2c3eb0e0 » | netguru | 2008-08-31 | 46 | ==Copyright | |
| 378af411 » | netguru | 2008-08-31 | 47 | ||
| 48 | Copyright (c) 2008 Michal Szajbe (http://codetunes.com) and netguru (http://netguru.pl), released under the MIT license | ||||
