如何在 laravel 中建立关系?

How to make alise of relation in laravel?

我的代码是:

     $this->model
        ->whereId($id)
        ->with('userRegion.region')
        ->first();

响应是

    "id": xx,
    "first_name": "sahil",
    "last_name": "gupta",
    "email": "xxxx@yopmail.com",
    "role_id": 0,
    "user_region":[] 

但我想将 user_region 的别名重命名或创建为 regions,然后它应该如下所示:

        "id": xx,
        "first_name": "sahil",
        "last_name": "gupta",
        "email": "xxxx@yopmail.com",
        "role_id": 0,
        "regions":[] 

我试过:

      $this->model
        ->whereId($id)
        ->with('userRegion.region as regions')
        ->first();

       $this->model
            ->whereId($id)
            ->with(['userRegion as regions','userRegion.region'])
            ->first();

但是他们两个解决方案都不起作用并抛出错误。

如果要使用名称为 regions 的关系,只需将关系方法的名称定义为 regions:

public function regions() {
    return $this->hasMany(...);
}

所以你可以使用 $this->model->whereId($id)->with('regions.region') 。 响应将是:

        "id": xx,
        "first_name": "sahil",
        "last_name": "gupta",
        "email": "xxxx@yopmail.com",
        "role_id": 0,
        "regions":[....] 

并且可以保留原来的userRegion关系方式,所以在其他情况下仍然可以使用with('userRegions.region')。区域方法调用关系方法:

public function regions() {
    return $this->userRegion();
}

另一个解决方案:

通过API Resources

userRegions重置为regions
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'role_id' => $this->role_id,
            'regions' => RegionResource::collection($this->userRegions),
            ...
        ];
    }