Laravel eloquent UUID in a pivot table

岁酱吖の 提交于 2019-12-03 22:56:10

问题


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?


回答1:


I think this might be what you want:

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

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

Update

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

i didn't test this code so i don't know if it will work or not, this is just an idea

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

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



来源:https://stackoverflow.com/questions/43240247/laravel-eloquent-uuid-in-a-pivot-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!