如何在幼虫 10.x 中为枢轴字段创建访问器?

How to create an accessor for pivot field in larval 10.x?

提问人:mostafa amiri 提问时间:10/28/2023 更新时间:10/28/2023 访问量:27

问:

我有两个模型:

  • 用户
  • 放置
    和枢轴为:
  • Role(user_id, place_id, type)
    和 type 的示例是 “[”manager“, ”reception“]” ,我想在检索为时将此值更改为 collection:
    Place::find(1)->users[0]->pivot->type

我添加了此方法,但它不起作用并返回字符串:

    public function getTypeAttribute($value){
        return collect(json_decode($value));
    }
PHP 转换 访问器 Laravel-10

评论

0赞 Mohit Nandpal 10/28/2023
您的数据透视表工作正常吗?如果是,则先尝试调试代码
0赞 mostafa amiri 10/28/2023
是的,它工作正常

答:

0赞 mostafa amiri 10/28/2023 #1

我忘了用.它应该是这样的:using$this->belongsToMany(Place::class, 'roles', 'place_id', 'user_id')->using(Role::class)->withPivot('type');