MongoDB驱动

这个扩展为Yii2框架提供了MongoDB的集成,允许你通过ActiveRecord风格的模型使用MongoDB collection的记录。

准备

  1. 按照官方指南http://www.yiiframework.com/doc-2.0/guide-start-installation.html的描述,使用Composer包管理器创建一个新的应用。
  2. https://docs.mongodb.org/manual/installation/使用正确的安装过程为你的系统安装MongoDB。
  3. 安装php5-mongo PHP扩展
  4. 使用如下命令安装组件:
  1. composer require yiisoft/yii2-mongodb

如何做…

  1. 首先,创建新的MongoDB数据库。在mongo-clientshell中运行它,并输入数据库的名称:
  1. mongo
  2. > use mydatabase
  1. 添加连接信息到你的components配置部分:
  1. return [
  2. // ...
  3. 'components' => [
  4. // ...
  5. 'mongodb' => [
  6. 'class' => '\yii\mongodb\Connection',
  7. 'dsn' => 'mongodb://localhost:27017/mydatabase',
  8. ],
  9. ],
  10. ];
  1. 添加新的控制台控制器到你的控制台配置文件中:
  1. return [
  2. // ...
  3. 'controllerMap' => [
  4. 'mongodb-migrate' => 'yii\mongodb\console\controllers\MigrateController'
  5. ],
  6. ];
  1. 使用shell命令创建新的migration:
  1. php yii mongodb-migrate/create create_customer_collection
  1. 输入如下代码到up()down()方法中:
  1. <?php
  2. use yii\mongodb\Migration;
  3. class m160201_102003_create_customer_collection extends Migration
  4. {
  5. public function up()
  6. {
  7. $this->createCollection('customer');
  8. }
  9. public function down()
  10. {
  11. $this->dropCollection('customer');
  12. }
  13. }
  1. 应用migration:
  1. php yii mongodb-migrate/up
  1. 添加MongoDB调试板,以及模型生成器到你的配置中:
  1. <?php
  2. if (YII_ENV_DEV) {
  3. // configuration adjustments for 'dev' environment
  4. $config['bootstrap'][] = 'debug';
  5. $config['modules']['debug'] = [
  6. 'class' => 'yii\debug\Module',
  7. 'panels' => [
  8. 'mongodb' => [
  9. 'class' => 'yii\mongodb\debug\MongoDbPanel',
  10. ],
  11. ],
  12. ];
  13. $config['bootstrap'][] = 'gii';
  14. $config['modules']['gii'] = [
  15. 'class' => 'yii\gii\Module',
  16. 'generators' => [
  17. 'mongoDbModel' => [
  18. 'class' => 'yii\mongodb\gii\model\Generator'
  19. ]
  20. ],
  21. ];
  22. }
  1. 运行Gii生成器:

MongoDB驱动 - 图1

  1. 启动新的MongoDB Model Generator来为你的collection生成新的模型:

MongoDB驱动 - 图2

  1. 点击预览生成按钮
  2. 检查你是否有了新的模型app\models\Customer
  1. <?php
  2. namespace app\models;
  3. use Yii;
  4. use yii\mongodb\ActiveRecord;
  5. /**
  6. * This is the model class for collection "customer".
  7. *
  8. * @property \MongoId|string $_id
  9. * @property mixed $name
  10. * @property mixed $email
  11. * @property mixed $address
  12. * @property mixed $status
  13. */
  14. class Customer extends ActiveRecord
  15. {
  16. public static function collectionName()
  17. {
  18. return 'customer';
  19. }
  20. public function attributes()
  21. {
  22. return [
  23. '_id',
  24. 'name',
  25. 'email',
  26. 'address',
  27. 'status',
  28. ];
  29. }
  30. public function rules()
  31. {
  32. return [
  33. [['name', 'email', 'address', 'status'], 'safe']
  34. ];
  35. }
  36. public function attributeLabels()
  37. {
  38. return [
  39. '_id' => 'ID',
  40. 'name' => 'Name',
  41. 'email' => 'Email',
  42. 'address' => 'Address',
  43. 'status' => 'Status',
  44. ];
  45. }
  46. }
  1. 再次运行Gii,并生成CRUD:

MongoDB驱动 - 图3

  1. 检查你已经生成了CustomerController类,并运行新的customer管理页面:

MongoDB驱动 - 图4

  1. 你可以创建、更新和删除你的顾客数据。
  2. 在页面的底部查看调试板:

MongoDB驱动 - 图5

  1. 你可以看到整个MongoDB查询数以及完整的执行时间。点击计数badge和查询指示:

MongoDB驱动 - 图6

基本用法

你可以通过\yii\mongodb\Collection实例访问数据库和集合:

  1. $collection = Yii::$app->mongodb->getCollection('customer');
  2. $collection->insert(['name' => 'John Smith', 'status' => 1]);

为了执行find查询,你应该使用\yii\mongodb\Query

  1. use yii\mongodb\Query;
  2. $query = new Query;
  3. // compose the query
  4. $query->select(['name', 'status'])
  5. ->from('customer')
  6. ->limit(10);
  7. // execute the query
  8. $rows = $query->all();

注意:MongoDB文档id(“_id”字段)不是数量,是一个\MongoId类的实例。你不需要关心从整形或者字符串$id转换为\MongoId,因为查询创建会自动转换:

  1. $query = new \yii\mongodb\Query;
  2. $row = $query->from('item')
  3. ->where(['_id' => $id]) // implicit typecast to \MongoId
  4. ->one();

为了获取真实的Mongo ID字符串,你应该将\MongoId做类型转为字符串:

  1. $query = new Query;
  2. $row = $query->from('customer')->one();
  3. var_dump($row['_id']); // outputs:
  4. "object(MongoId)"var_dump((string)$row['_id']);

工作原理…

这个扩展的QueryActiveQuery以及ActiveRecord继承了yii\db\QueryInterfaceyii\db\BaseActiveRecord。因此他们和框架内置的QueryActiveQuery以及ActiveRecord是兼容的。

你可以为你的模型使用yii\mongodb\ActiveRecordyii\mongodb\ActiveQuery构建器来获取你的模型,并在你的data provider使用他们:

  1. use yii\data\ActiveDataProvider;
  2. use app\models\Customer;
  3. $provider = new ActiveDataProvider([
  4. 'query' => Customer::find(),
  5. 'pagination' => [
  6. 'pageSize' => 10,
  7. ]
  8. ]);

关于如何使用Yii ActiveRecord的一般信息,请参考第三章,ActiveRecord,模型和数据库

参考