Last active
December 20, 2022 02:26
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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