> 使用官方提供的yii2-mongodb擴展即可實現
> https://github.com/yiisoft/yii2-mongodb
### 安裝擴展
~~~
php composer.phar require --prefer-dist yiisoft/yii2-mongodb
~~~
### 配置mongodb數據庫
> main-local.php
~~~
return [
//....
'components' => [
'mongodb' => [
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://@localhost:27017/mydatabase',
'options' => [
"username" => "Username",
"password" => "Password"
]
],
],
];
~~~
### 創建 ActiveRecord 模型
~~~
namespace common\mongomodels;
use common\behaviors\DatetimeBehavior;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* SMS日志記錄
* This is the model class for table "sms_log".
*
* @property \MongoDB\BSON\ObjectID|string $_id
* @property string $mobile
* @property string $code
* @property integer $type
* @property integer $created_at
* @property integer $updated_at
*/
class SmsLog extends \yii\mongodb\ActiveRecord
{
const TYPE_BIND = '1'; //綁定
const TYPE_CHECK_OLD = '2'; //驗證以前的
const TYPE_CHANGE = '3'; //修改
const TYPE_WITHDRAW = '4'; //提現
/**
* @inheritdoc
*/
public static function collectionName()
{
return ['test', 'sms_log'];
}
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['mobile', 'code', 'type'], 'required'],
[['type'], 'string'],
[['type'], 'in', 'range' => [self::TYPE_BIND, self::TYPE_CHECK_OLD, self::TYPE_CHANGE, self::TYPE_WITHDRAW]],
[['created_at', 'updated_at'], 'safe'],
[['mobile', 'code'], 'string', 'max' => 50],
];
}
/**
* @inheritdoc
*/
public function attributes()
{
return [
'_id',
'mobile',
'code',
'type',
'created_at',
'updated_at',
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'mobile' => '手機號',
'code' => '驗證碼',
'type' => '類型',
'created_at' => '創建時間',
'updated_at' => '更新時間',
];
}
}
~~~
### 使用 ActiveRecord CRUD 例子
~~~
$smslog = SmsLog::findOne(['mobile' => $mobile, 'type' => SmsLog::TYPE_BIND]);
$smslog->mobile = 'xxx';
$smslog->save();
~~~
- 基礎教程
- 入門安裝
- Yii2 composer 安裝慢解決
- Cookies
- 數據庫操作
- 數據提供者
- 助手類
- 驗證規則
- GridView
- DetailView
- YII2分頁
- JS、CSS的引用
- Excel導出
- 中文轉拼音
- 發送郵件
- 第三方插件
- Session跨域共享
- Url跨域訪問
- 場景應用
- 查詢條件鏈
- Session分布式共享
- Redis的使用
- mongodb
- 高級教程
- 自定義gii模板
- 角色權限管理(RBAC)
- user組件的配置
- 國際化(I18N)
- 小部件(Widget)
- 模塊(Module)
- 行為(Behavior)
- 緩存(Cache)
- migrate 數據庫遷移
- phpstorm
- 快捷鍵
- 自定義
- 其它插件