advanced.primary-key.txt 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. Title: Primary Keys
  2. Author: Dariusz Górecki <darek.krk@gmail.com>
  3. ---
  4. By default YiiMongoDbSuite will always use the `_id` field as a collection primary key.
  5. > [information]
  6. > MongoDB itself guarantee that `_id` field will be unique across collection.
  7. # The `_id` field {#_id}
  8. The `_id` field in a short is, be default an instance of `MongoID` class.
  9. If you will do `echo $model->_id` you will see something like: `'4ced75e1eb4ae8ca44000000'`
  10. This is basically, the textual representation of auto-generated by MongoDB _id field.
  11. **But be aware that MongoID is not a string!**
  12. *This will not find anything! `$model->findByPk('4ced75e1eb4ae8ca44000000');`*
  13. To find an model with specified ID use:
  14. `$model->findByPk(new MongoID('4ced75e1eb4ae8ca44000000'));`
  15. > [information]
  16. > ### You can put **any** value into an `_id` field
  17. > MongoDB will auto populate _id field by MongoID objects **only when** it is set to `NULL`
  18. # Own defined Primary Key for collection {#ownpk}
  19. You can define a own field to be used as a Primary Key for yours collection, see example:
  20. ~~~
  21. [php]
  22. class Client extends EMongoDocument
  23. {
  24. // ...
  25. // Define primaryKey method:
  26. public function primaryKey()
  27. {
  28. return 'personal_number'; // Model field name, by default the _id field is used
  29. }
  30. // Now you can:
  31. // Client::model()->findByPk(1234); // personal_number == 1234
  32. // ...
  33. }
  34. ~~~