advanced.named-scopes.txt 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. Title: Named Scopes
  2. Author: Dariusz Górecki <darek.krk@gmail.com>
  3. ---
  4. Now you can use AR style named scopes just define scopes method in yours model:
  5. ~~~
  6. [php]
  7. class Client extends EMongoDocument
  8. {
  9. // (...)
  10. public function scopes()
  11. {
  12. return array(
  13. 'scopeName'=>array(/* Array for criteria object creation see Criteria from array topic */),
  14. );
  15. }
  16. public function defaultScope()
  17. {
  18. return array(
  19. 'conditions'=>array(
  20. 'active'=>array('==', true),
  21. ),
  22. );
  23. }
  24. // (...)
  25. }
  26. // now You can:
  27. // this will find only clients that are active (default scope) and clients matching 'scopeName'
  28. $all = Client::model()->scopeName()->findAll();
  29. ~~~
  30. # Parameterized Named Scopes {#pns}
  31. ~~~
  32. [php]
  33. class Client extends EMongoDocument
  34. {
  35. // (...)
  36. public function byStatus($status)
  37. {
  38. $criteria = $this->getDbCriteria();
  39. $criteria->status = $status;
  40. $this->setDbCriteria($criteria);
  41. return $this;
  42. }
  43. // (...)
  44. }
  45. // now You can:
  46. // this will find only clients that have status set to parameter value:
  47. $all = Client::model()->byStatus(1)->findAll();
  48. ~~~
  49. > [information]
  50. > ### You can chain multiple named scopes
  51. > example: `Client::model()->active()->byStatus(1)->findAll();`