basic.simple-model.txt 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. Title: Simple Model (Document in collection)
  2. ShortTitle: Simple Model
  3. Author: Dariusz Górecki <darek.krk@gmail.com>
  4. ---
  5. For basic use, just declare simple model, under yours application models directory,
  6. we will show simple User model that will represent documents stored in `users` MongoDB collection.
  7. ~~~
  8. [php]
  9. class User extends EMongoDocument // Notice: We extend EMongoDocument class instead of CActiveRecord
  10. {
  11. public $personal_no;
  12. public $login;
  13. public $first_name;
  14. public $last_name;
  15. public $email;
  16. /**
  17. * This method have to be defined in every Model
  18. * @return string MongoDB collection name, witch will be used to store documents of this model
  19. */
  20. public function getCollectionName()
  21. {
  22. return 'users';
  23. }
  24. // We can define rules for fields, just like in normal CModel/CActiveRecord classes
  25. public function rules()
  26. {
  27. return array(
  28. array('login, email, personal_no', 'required'),
  29. array('personal_no', 'numerical', 'integerOnly' => true),
  30. array('email', 'email'),
  31. );
  32. }
  33. // the same with attribute names
  34. public function attributeNames()
  35. {
  36. return array(
  37. 'email' => 'E-Mail Address',
  38. );
  39. }
  40. /**
  41. * This method have to be defined in every model, like with normal CActiveRecord
  42. */
  43. public static function model($className=__CLASS__)
  44. {
  45. return parent::model($className);
  46. }
  47. }
  48. ~~~
  49. Now we can star using our model, just as normal Yii ActiveRecord!
  50. ~~~
  51. [php]
  52. $user = new User();
  53. $user->personal_no = 1234;
  54. $user->login = 'somelogin';
  55. $user->email = 'email@example.com';
  56. $user->save(); // This will store document with user data into MongoDB collection
  57. ~~~