Yii2 Mongodb 生成递增id的方法

 

代码如下:

  1. public static function increament($tablename){
  2. $coll = Yii::$app->mongodb->getCollection("ids");
  3. $update = array('?inc'=>array('id'=>1));
  4. $query = array('name'=>$tablename);
  5. $command = array(
  6. 'findandmodify'=>'ids', 'update'=>$update,
  7. 'query'=>$query, 'new'=>true, 'upsert'=>true
  8. );
  9. $result = $coll->mongoCollection->db->command($command);
  10. $id = $result['value']['id'];
  11. $current_id = (int)$id->value;
  12. Global $current_id;
  13. return $current_id;
  14. }
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的递增字段,则可以使用下面的代码:

  1. function increament($m,$database_name,$collection_name){
  2. $ids = "ids";
  3. $db_name = "tracedb";
  4. $db = $m->selectDB($db_name);
  5. //$col = $m->selectDB($db_name)->$ids;
  6. $query = array('name'=>$collection_name);
  7. $update = array('$inc'=>array('id'=>1));
  8. $result = $db->command(
  9. array(
  10. "findandmodify" => $ids,
  11. "query" => $query,
  12. "update" => $update,
  13. 'new'=>true,
  14. 'upsert'=>true
  15. )
  16. );
  17. return $result['value']['id'];
  18. }
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'];
  
  

}

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注