Laravel 9.x中的常規錯誤:字段'id'在沒有預設值的情況下
P粉714780768
P粉714780768 2024-04-06 11:12:54
0
1
338

我在我的應用程式中使用 UUID,並且我已經實現了該特徵,如在線所示,如下所示:

trait Uuid
{
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (Model $model) {
            if (!$model->getKey()) {
                $model->{$model->getKeyName()} = (string) Str::uuid();
            }
        });
    }

    public function getIncrementing(): bool
    {
        return false;
    }

    public function getKeyType(): string
    {
        return 'string';
    }
}

回想起來,這幾乎適用於任何地方:我正在嘗試在我的產品上建立資料透視表,如下所示:

public function categories(): BelongsToMany
{
    return $this->belongsToMany(
        Category::class,
        ProductCategory::class,
        'product_id',
        'category_id'
    );
}

遷移如下圖所示:

public function up(): void
{
    Schema::create('product_categories', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->foreignUuid('product_id')->index();
        $table->foreignUuid('category_id')->index();
        $table->timestamps();
    });
}

但是,每當我在播種時執行以下操作:

Product::first()->categories()->sync(Categories::all()->pluck('id'));

我看到這個錯誤:

PDOException::(“SQLSTATE[HY000]:一般錯誤:1364 欄位「id」沒有預設值」)

CategoryProductCategory 都使用 Uuidd 特徵,我不知道如何使其工作。

感謝任何幫助。

P粉714780768
P粉714780768

全部回覆(1)
P粉731977554

作為可能的解決方案之一,您可以使用自己的模型和資料透視表的特徵。

更多: https://laravel.com/docs/ 9.x/eloquent-relationships#defining-custom-intermediate-table-models

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!