Laravel 10 Mongodb Use AutoIncrement ID

Laravel 10 Mongodb Use AutoIncrement ID

MongoDB hiện nay không có chức năng Auto Increment, như cơ sở dữ liệu SQL. Theo mặc định, Mongodb sử dụng ObjectId 12 byte cho trường _id làm khóa chính để nhận dạng duy nhất các tài liệu .Vấn đề sảy ra sẽ khó cho các bạn mới làm chuyển từ MySQL sang Mongodb .Ở dưới đây chúng ta sẽ sử dụng 1 collection dữ liệu : sequences

Trong file :  app/Models/Sequence.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use MongoDB\Laravel\Eloquent\Model;

//use Illuminate\Database\Eloquent\Model;

class Sequence extends Model
{
//    use HasFactory;
    protected $collection='sequences';
    protected $fillable = [
        'name',
        'next_sequence',
    ];
}

1 Tạo trait để dễ import vào các model

Ở đây chúng ta tạo 1 file trait để có thể import vào các model cần sử dụng : app/Traits/UseAutoIncrementID.php

 

<?php
namespace App\Traits;

use App\Models\Sequence;

trait UseAutoIncrementID
{
    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $sequenceName = (new static)->getTable();
            $sequence = Sequence::where('name', $sequenceName)->first();
            if ($sequence) {
                $model->id = $sequence->next_sequence;
                $sequence->increment('next_sequence');
            } else {
                $sequence = Sequence::create([
                    'name' => $sequenceName,
                    'next_sequence' => 1,
                ]);
                $model->id = 1;
            }
        });
    }
}

Bây giờ ở các collection mà bạn muốn auto increment chúng ta chỉ cần thêm trait UseAutoIncrementID vào ví dụ như sau : 

<?php

namespace App\Models;

use App\Traits\UseAutoIncrementID;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Post extends \MongoDB\Laravel\Eloquent\Model
{
    use HasFactory,UseAutoIncrementID;

    protected $guarded=['id'];
    protected $index = [
        'slug' => 'text', // Tạo một chỉ mục văn bản cho trường 'email'

    ];

    public function setSlugAttribute($value)
    {
        $this->attributes['slug'] = Str::slug($value);
    }
}