Php 使用Jenssers mongodb laravel的自动增量id
我需要自动生成id序列 我使用的是Php 使用Jenssers mongodb laravel的自动增量id,php,laravel,jenssegers-mongodb,Php,Laravel,Jenssegers Mongodb,我需要自动生成id序列 我使用的是jenssegers 我有一个来自的useautomincrementid特征 并将其用作: use App\Traits\UseAutoIncrementID; .... .... $data['_id'] = $this->getID('request_feeds'); // request_feeds is collection name. 我得到这个错误: (1/1) FatalThrowableError Call to undefined m
jenssegers
我有一个来自的useautomincrementid特征
并将其用作:
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序列
在模型中,添加以下方法:
在控制器中,创建一个新集合并使用nextid()方法-示例:
在模型中,添加以下方法:
在控制器中,创建一个新集合并使用nextid()方法-示例:
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();