Laravel eloquent 枢轴中的 UUID table

Laravel eloquent UUID in a pivot table

这道题是这样的:。但是,这个问题的不同之处在于 table 是一个枢轴 table,id 字段使用通过插入时 MySQL 触发器生成的 UUID。

我不想为该枢轴创建另一个模型 table 来为其提供类似问题答案所考虑的解决方案。那么,有什么方法可以从与其相关的另一个模型中执行枢轴 table 的类型转换吗?

我想这可能是你想要的:

在定义 BelongsToMany 关系的模型中添加此 属性:

protected $casts = ['relationName.pivot.id' => 'string'];

更新

我想我们可以在这里使用 php7.0 中的匿名 classes 而不是为数据透视创建模型 class:

我没有测试这段代码所以我不知道它是否有效,这只是一个想法

public function activeStatuses()
{
    return $this->belongsToMany('ModelName')
                ->using(class_basename(new class extends \Illuminate\Database\Eloquent\Relations\Pivot {
                    protected $casts = ['id' => 'string'];
                }));
}

通常我更愿意为枢轴创建模型 table 或者简单地使用

对我有用:

// 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());
        });
    }
}