basic.embedded-documents.txt 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. Title: Embedded Documents
  2. Author: Dariusz Górecki <darek.krk@gmail.com>
  3. ---
  4. # Basic informations about embedded documents
  5. ## Must know: {#mustknow}
  6. - For performance reasons all models of embedded documents should extend from `EMongoEmbeddedDocument` class
  7. - But the above is not a must, things will still work if you define as embedded child classes of regular `EMongoDocument`
  8. - You can define as many embedded documents as you wish
  9. - Every embedded document **can contain** embedded documents!
  10. - The only limit for this mechanism is that serialized version (in raw array format) of whole document, must not extend the 4 MB size
  11. - For documents bigger than 4 MB see the [GridFS Section][advanced.gridfs]
  12. - Main difference between `EMongoDocument` and EMongoEmbeddedDocument` is that:
  13. - EMongoDocument extends from EMongoEmbeddedDocument
  14. - EMongoDocument is equipped with all methods needed to save its contents into a MongoDB collection
  15. - You cannot call ie `save()` method on a EMongoEmbeddedDocument
  16. ## Defining embedded documents within document {#defining}
  17. **This applies to EMongoDocument and EMongoEmbeddedDocument**
  18. Just define the `embeddedDocuments()` method in yours model class, it should return array of
  19. simple key => value pairs.
  20. - Array values are class names that will be used to instantinate embedded documents
  21. - Array keys are treated as property names of given embedded document class
  22. example:
  23. ~~~
  24. [php]
  25. // ...
  26. // within model class
  27. public function embeddedDocuments()
  28. {
  29. return array(
  30. 'address' => 'UserAddress',
  31. 'some_other_field_name' => 'AnyEMongoEmbeddedDocumentChildClass',
  32. );
  33. }
  34. // this will give you access to propeties of model:
  35. $model->address->embeddedExampleField;
  36. $model->some_other_field_name->embeddedExampleField;
  37. ~~~
  38. ## How to force save of embedded document into collection {#forcesave}
  39. - First we need to get the mongo collection object ie:
  40. - `$collection = SomeModelClass::model()->getCollection();`
  41. - `$collection = SomeModelClass::model()->getDb()->collectionName;`
  42. - `$collection = Yii::app()->getComponent('mongodb')->getConnection()->collectionName;`
  43. - When we have our collection model, we now can force save of embedded document as a regular root document:
  44. - `$collection->save($ourEmbeddedModel->toArray());`