yii2 使用mongodb

引入 yiisoft/yii2-mongodb
composer require --prefer-dist yiisoft/yii2-mongodb
<?php

namespace api\v1\controllers;

use api\common\controllers\CommonController;
use yii\mongodb\Query;
use yii\data\ActiveDataProvider;
use common\models\Mymongo;
use Yii;

class MongoController extends CommonController
{
    public function actionInsert()
    {
        //  insert 操作
        $collection = Yii::$app->mongodb->getCollection('customer');
        $res = $collection->insert([
        'name' => 'wbj',
        'age' => 30
        ]);
        return $res;
    }

    public function actionList()
    {
        $query = new Query();
        $query->select([
        'name',
        ])->from('customer')->offset(10)->limit(10);
        $rows = $query->all();
        return $rows;
    }
    
    public function actionOne()
    {
        $query = new Query();
        $row = $query->from('customer')->one();
        return $row;
    }
    
    public function actionFind()
    {
        $provider = new ActiveDataProvider([
        'query' => Customer::find(),
        'pagination' => [
        'pageSize' => 10
        ]
        ]);
        $models = $provider->getModels();
        var_dump($models);
    }
    
    public function actionProvider()
    {
        $query = new Query();
        $query->from('customer')->where([
        'status' => '222'
        ]);
        $provider = new ActiveDataProvider([
        'query' => $query,
        'pagination' => [
        'pageSize' => 10
        ]
        ]);
        $models = $provider->getModels();
        var_dump($models);
    }
    
    public function actionSave()
    {
        $res = Customer::saveInfo();
        return $res;
    }
}

<?php
namespace common\models;

class Customer extends \yii\mongodb\ActiveRecord
{
    public static function collectionName()
    {
        return 'customer';
    }
    public function saveInfo()
    {
        $customer = new Customer ();
        $customer->name = '111';
        $customer->email = '222';
        $customer->status = '222';
        $customer->insert();
        return $customer;
    }
    public function attributes()
    {
        return [
        '_id',
        'name',
        'email',
        'address',
        'status'
        ];
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值