ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> 使用官方提供的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(); ~~~