Fecshop 2016-12-09 08:44:40 6052次浏览 3条评论 0 0 0

原文链接:Yii2 Mongodb 生成递增id的方法

Mongodb中的id为uuid,现在我们想要递增id的方式。
代码如下:

    public static function increament($tablename){
        
        $coll = Yii::$app->mongodb->getCollection("ids");
        $update = array('?inc'=>array('id'=>1));
        $query = array('name'=>$tablename);
        $command = array(
          'findandmodify'=>'ids', 'update'=>$update,
          'query'=>$query, 'new'=>true, 'upsert'=>true
          );
        
        $result = $coll->mongoCollection->db->command($command);
        $id = $result['value']['id'];
        
        $current_id = (int)$id->value;
        Global $current_id;
        return $current_id;
      }

使用的时候直接 $dd = CID::increament(‘xxx’);即可获取到递增的id,

在一些场景,插入压力不是很多,但是很需要递增id的场景可以使用mongodb的这种递增id的方式,上面的写法是在yii2中使用的写法,如果不在yii2中使用mongodb的递增字段,则可以使用下面的代码:

    function increament($m,$database_name,$collection_name){
      
      $ids = "ids";
      $db_name = "tracedb";
      $db = $m->selectDB($db_name);
      //$col = $m->selectDB($db_name)->$ids;
      
      $query = array('name'=>$collection_name);
      $update = array('$inc'=>array('id'=>1));
      $result = $db->command(
                array(
                "findandmodify" => $ids,
                "query" => $query,
                "update" => $update,
                'new'=>true,
                'upsert'=>true
                )
              );
      return $result['value']['id'];
      
      
    }
  • 评论于 2016-12-09 23:51 举报

    最后,推荐一下我的Fecshop ,开源商城,github地址:https://github.com/fancyecommerce/yii2_fecshop

    演示地址:http://fecshop.appfront.fancyecommerce.com/

    截止到2016-11-12号,产品,分类,首页,评论,用户中心,搜索,多语言,多货币 等功能已经做完,除了购物车和支付部分,其他的基本都已经完成,关注fecshop的 在等2-3个月,也就是明年2,3月份,版本已经就可以出来,2017年4,5月份在把手机web 做一下,预计到明年5月份,后台,pc前台,手机web前台 ,命令控制台 这几个入口 基本可以完善,多谢大家关注和你们的Star,谢谢,我会坚持把他写好。

    作者QQ:2358269014

  • 评论于 2018-09-04 18:23 举报

    $result = \Yii::$app->db->getCollection('ids')->findandmodify(

    ['name'=>static::collectionName()],
    ['$inc'=>array('id'=>1)],
    ['upsert'=>true,'fields' => 'id']
    );
    

    return $result['id'];

    这样就可以了吧

    1 条回复
    评论于 2018-10-10 14:57 回复

    可以自己测试一下

  • 评论于 2019-04-29 15:11 举报

    上面两种方法我都做了测试:

    // 上面的方法可能有问题 改为下方二种方法
    
            // 方法一:(对应原作者)
            // $update  = ['?inc' => ['id' => 1]];
            // $query   = ['name' => static::collectionName()];
            // $command = [
            //     'findandmodify' => 'ids', 'update' => $update,
            //     'query'         => $query, 'new' => true, 'upsert' => true
            // ];
            // $result = current($coll->database->createCommand($command)->execute()->toArray());
    
            // 方法二:(对应kero)
            $result = $coll->findandmodify(
                ['name' => 'ids'],
                ['?inc' => ['id' => 1]],
                ['upsert' => true, 'fields' => 'id', 'new' => true]
            );
            return $result['_id'];
    
您需要登录后才可以评论。登录 | 立即注册