advanced.relations.txt 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. Title: Relations
  2. Author: Dariusz Górecki <darek.krk@gmail.com>
  3. ---
  4. - In NoSQL World Relations are not so obvious as in RDBMS
  5. - Because NoSQL databases are designed for performance, there is no need of defining something more complex than correct use of find() method and indexing for fetching related records
  6. - This is just an *idea/concept/example* you can do things in yours preferred way! this is schema-less world, think different!
  7. - MongoDB Documentation has a clean examples and how-to's for handling relations, *please* read them for better understanding of relations in NoSQL world
  8. # HAS_ONE relation {#hasone}
  9. ~~~
  10. [php]
  11. // just define method in yours model class (assume we have client collection, and address collection in client model
  12. public function address()
  13. {
  14. return Address::model()->findByAttributes(array('attribute_with_client_id'=>$this->primaryKey()));
  15. }
  16. ~~~
  17. # BELONGS_TO relation {#belongsto}
  18. ~~~
  19. [php]
  20. // define in address model
  21. public function client()
  22. {
  23. return Client::model()->findByPk($this->attribute_with_client_id);
  24. }
  25. ~~~
  26. # HAS_MANY relation {#hasmany}
  27. ~~~
  28. [php]
  29. // assume we have clients and orders collection
  30. // define in client:
  31. public function orders()
  32. {
  33. return Client::model()->findAllByAttributes(array('client_id'=>$this->primaryKey()));
  34. }
  35. ~~~
  36. # MANY_MANY relation {#manymany}
  37. As simple as defining reverse HAS_MANY relation in orders model. You can view the Example models for details.