与jenssegers mongodb laravel一起使用自动增量ID

时间:2019-04-29 09:39:16

标签: php laravel jenssegers-mongodb

我需要自动生成ID序列。

我正在使用jenssegers

我有一个来自hereUseAutoIncrementID 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序列?

1 个答案:

答案 0 :(得分:0)

  1. 在模型中,添加以下方法:
    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;
    }

  1. 在您的控制器中,创建一个新集合并使用nextid()方法-示例:
$car = new Car();
$car->nextid(); // auto-increment
$car->name = "Ferrari",
$car->save();