数据透视表中的 Laravel 雄辩的 UUID雄辩、透视、数据、Laravel

由网友(海绵宝宝的笑)分享简介:这个问题是这样的:laravel uuid not shown in query.但是,这个问题的不同之处在于该表是一个带有 id 字段的数据透视表,它使用通过 MySQL 插入时触发器生成的 UUID.This question is like this one: laravel uuid not showing...

这个问题是这样的:laravel uuid not shown in query.但是,这个问题的不同之处在于该表是一个带有 id 字段的数据透视表,它使用通过 MySQL 插入时触发器生成的 UUID.

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 id field uses UUID generated via MySQL trigger on insert.

我不想为该数据透视表创建另一个模型来为其提供类似问题的答案所考虑的解决方案.那么,有没有办法从与之相关的另一个模型中执行数据透视表的类型转换?

I don't want to create another model for that pivot table to supply it with the solution regarded on the similar question's answer. So, is there any way to perform type casting of the pivot table from another model related to it?

推荐答案

我想这可能是你想要的:

I think this might be what you want:

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

In your model that defines the BelongsToMany relationship add this property:

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

更新

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

I guess we can make use of anonymous classes in php7.0 here instead of creating a model class for the pivot:

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

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

一般来说,我更愿意为数据透视表创建模型或简单地使用 数据透视类

Generally i would prefer to create model for the pivot table or simply use a pivot class

阅读全文

相关推荐

最新文章