php Laravel数据透视表中的UUID

fdx2calv  于 12个月前  发布在  PHP
关注(0)|答案(3)|浏览(99)

这个问题是这样的:**laravel uuid not showing in query* 然而,这个问题的区别在于,表是一个带有id字段的透视表,在插入时使用通过MySQL触发器生成的UUID。
我不想为这个数据透视表创建另一个模型,以提供类似问题答案的解决方案。那么,有没有办法从另一个与之相关的模型中执行数据透视表的类型转换?

qoefvg9y

qoefvg9y1#

我想这可能是你想要的:
在定义了BelongsToMany关系的模型中,添加以下属性:

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

字符串

更新

我想我们可以在这里使用php7.0中的匿名类,而不是为pivot创建一个模型类:

  • 我没有测试这个代码,所以我不知道它是否会工作,这只是一个想法 *
public function activeStatuses()
{
    return $this->belongsToMany('ModelName')
                ->using(class_basename(new class extends \Illuminate\Database\Eloquent\Relations\Pivot {
                    protected $casts = ['id' => 'string'];
                }));
}


一般来说,我更喜欢为数据透视表创建模型,或者简单地使用pivot class

xwbd5t1u

xwbd5t1u2#

它对我有效:

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

个字符

brtdzjyr

brtdzjyr3#

从Laravel 9开始,你可以将trait HasUuids传递给新的示例:

/**
     * @return BelongsToMany<\App\Models\ExampleModel>
     */
    public function tags(): BelongsToMany
    {
        return $this
            ->belongsToMany(\App\Models\ExampleModel::class)
            ->using(new class extends \Illuminate\Database\Eloquent\Relations\Pivot; {
                use \Illuminate\Database\Eloquent\Concerns\HasUuids;
            });
    }

字符串
另一种方法是创建一个pivot类并在那里设置这个use语句。然而,这一点被提问者排除在外。

相关问题