Laravel eloquent UUID in a pivot table

后端 未结 2 2072
Happy的楠姐
Happy的楠姐 2021-01-07 06:27

This question is like this one: laravel uuid not showing in query. However, the difference in this question is about that table is a pivot table with

2条回答
  •  攒了一身酷
    2021-01-07 06:41

    It works for me:

    // use Illuminate\Database\Eloquent\Relations\Pivot;
    return $this->belongsToMany(Vendor::class, 'vendors_has_geo_cities', 'city_id', 'vendor_id')
                ->using(new class extends Pivot {
                    use UuidTrait;
                });
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Support\Str;
    
    trait UuidTrait
    {
        public function initializeUuidTrait(): void
        {
            $this->setIncrementing(false);
            $this->setKeyType('string');
        }
    
        /**
         * The "booting" method of the model.
         *
         * @return void
         */
        protected static function bootUuidTrait()
        {
            self::creating(function (Model $model) {
                $model->setAttribute($model->getKeyName(), Str::orderedUuid());
            });
        }
    }
    

提交回复
热议问题