【问题标题】:How to make alise of relation in laravel?如何在laravel中建立关系?
【发布时间】:2020-05-01 12:23:47
【问题描述】:

我的代码是:

     $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": [{..., "region": []}, {...}]}吗?
  • @TsaiKoga 我刚刚更新了我的问题。请检查...

标签: database laravel eloquent laravel-models


【解决方案1】:

如果要使用名称为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')。而regions方法调用relationship方法:

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

另一种解决方案:

API ResourcesuserRegions 重置为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),
            ...
        ];
    }

【讨论】:

  • 我们不能创建alise?
  • 为同一个关系创建两个不同的函数是DRY原则的暴力。
  • @SahilGupta在regions()方法中,可以调用关系方法userRegion,也可以通过resources改键
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 2015-01-20
  • 1970-01-01
  • 2021-12-17
  • 2020-06-28
  • 2020-01-18
  • 2020-08-28
相关资源
最近更新 更多