我需要自动生成ID序列。
我正在使用jenssegers
。
我有一个来自here的UseAutoIncrementID trait
。
并将其用作:
use App\Traits\UseAutoIncrementID;
....
....
$data['_id'] = $this->getID('request_feeds'); // request_feeds is collection name.
我收到此错误:
(1/1) FatalThrowableError
Call to undefined method Illuminate\Database\MySqlConnection::getCollection()
如何使用jenssegers
获取自动生成的ID序列?
答案 0 :(得分:0)
public function nextid()
{
// ref is the counter - change it to whatever you want to increment
$this->ref = self::getID();
}
public static function bootUseAutoIncrementID()
{
static::creating(function ($model) {
$model->sequencial_id = self::getID($model->getTable());
});
}
public function getCasts()
{
return $this->casts;
}
private static function getID()
{
$seq = DB::connection('mongodb')->getCollection('counters')->findOneAndUpdate(
['ref' => 'ref'],
['$inc' => ['seq' => 1]],
['new' => true, 'upsert' => true, 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER]
);
return $seq->seq;
}
$car = new Car();
$car->nextid(); // auto-increment
$car->name = "Ferrari",
$car->save();