Skip to content

Instantly share code, notes, and snippets.

@iRbouh
Last active December 20, 2022 02:26
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iRbouh/d244ff8ad05dbbce417a0b664d2d89a4 to your computer and use it in GitHub Desktop.
Save iRbouh/d244ff8ad05dbbce417a0b664d2d89a4 to your computer and use it in GitHub Desktop.
Auto incrementing sequence Trait to use with jenssegers/laravel-mongodb for AI MySQL-like IDs
<?php
namespace App\Traits;
trait UseAutoIncrementID {
/**
* Increment the counter and get the next sequence
*
* @param $collection
* @return mixed
*/
private static function getID($collection) {
$seq = \DB::getCollection('_data_counters')->findOneAndUpdate(
array('_id' => $collection),
array('$inc' => array('seq' => 1)),
array('new' => true, 'upsert' => true, 'returnDocument' => \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER)
);
return $seq->seq;
}
/**
* Boot the AutoIncrementID trait for the model.
*
* @return void
*/
public static function bootUseAutoIncrementID() {
static::creating(function ($model) {
$model->incrementing = false;
$model->{$model->getKeyName()} = self::getID($model->getTable());
});
}
/**
* Get the casts array.
*
* @return array
*/
public function getCasts() {
return $this->casts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment