ThinkPHP Mongo驱动update方法支持upsert参数

Mongo数据库update操作有一个相对于Mysql的关键特性,它可以使用upsert模式,当更新的数据不存在时,直接插入,但是ThinkPHP的Mongo驱动居然不支持这一特性,没办法,自力更生了。

ThinkPHP的driver层,见由于支持多种DB,又使用了继承,使用得类层次结构较深,负责Mongo驱动的是DbMongo.class.php,文件位于ThinkPHP\Extend\Driver\Db,修改Update方法的$options参数,如果update方法提供了upsert选项时,就以upsert模式更新MongoDB。

   1:  public function update($data,$options) {
   2:          if(isset($options['table'])) {
   3:              $this->switchCollection($options['table']);
   4:          }
   5:          $this->model  =   $options['model'];
   6:          N('db_write',1);
   7:          $query   = $this->parseWhere($options['where']);
   8:          $set  =  $this->parseSet($data);
   9:          $isUpsert = $options['upsert'] === true ? true : false;
  10:          if($this->debug) {
  11:              $this->queryStr   =  $this->_dbName.'.'.$this->_collectionName.'.update(';
  12:              $this->queryStr   .= $query?json_encode($query):'{}';
  13:              $this->queryStr   .=  ','.json_encode($set).')';
  14:          }
  15:          try{
  16:              // 记录开始执行时间
  17:              G('queryStartTime');
  18:              $result   = $this->_collection->update($query,$set,array("upsert" => $isUpsert, "multiple" => true));
  19:              $this->debug();
  20:              return $result;
  21:          } catch (MongoCursorException $e) {
  22:              throw_exception($e->getMessage());
  23:          }
  24:      }

这样使用update方法

   1:  $criteria[FollowerModel::UID] = $uid; 
   2:  $this->follower_model->where($criteria)->save($data, array('upsert'=>true));

转载于:https://www.cnblogs.com/BlankEye/archive/2012/11/24/2786382.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值