【问题标题】:Laravel Multi level relationship in API ResourceLaravel API 资源中的多级关系
【发布时间】:2019-06-23 10:22:31
【问题描述】:

我的问题是,我真的不需要加载 api 资源。 查看我的 Api 资源文件

//BoxItemResource.php

 public function toArray($request)
{
    return [
        'box_id'=> $this->box_id,
        'item_id'=> $this->item_id,
        'item'=> new ItemResource($this->item)
    ];
}

//ItemResource.php

public function toArray($request)
{
    return [
        'id' => $this->id,
        'shipping_price' => $this->shipping_price,
        'condition_id' => $this->condition_id,
        'condition' => new ConditionResource($this->condition)
    ];
}

//ConditionResource.php

public function toArray($request)
{
    return [
        'id'=> $this->id,
        'name'=> $this->name
    ];
}

//控制器

return BoxItemResource::collection(
        BoxItem::with([
            'item'
        ])->paginate(1)
    );

我的问题是,我只需要 BoxItem 和 Item 这里。我真的不想加载条件。 如果我从 ItemResource.php 中删除条件关系,它将起作用。但问题是我在其他需要此条件的地方使用 ItemResource.php。

这里可以否认装货条件关系吗?

更清楚地说,我想加载我在 controller(in ->with()) 中提到的关系。

提前致谢。

【问题讨论】:

    标签: laravel laravel-resource


    【解决方案1】:

    API 资源允许 conditional attribtuesconditional relationships

    对于我认为在您的情况下足以使用的属性,这意味着您可以简单地将属性值包装在$this->when($condition, $value) 中,如果$condition == false,整个属性将从结果中删除。所以你的代码的一个具体例子:

    return [
        'box_id'=> $this->box_id,
        'item_id'=> $this->item_id,
        'item'=> $this->when($this->relationLoaded('item'), new ItemResource($this->item))
    ];
    

    或者,如果您更喜欢使用关系样式:

    return [
        'box_id'=> $this->box_id,
        'item_id'=> $this->item_id,
        'item'=> new ItemResource($this->whenLoaded('item'))
    ];
    

    【讨论】:

    • 非常感谢 Namoshek。
    【解决方案2】:

    也许您正在寻找Conditional Relationships

    理想情况下,它应该如下所示:

    public function toArray($request)
    {
        return [
            'box_id'=> $this->box_id,
            'item' => ItemResource::collection($this->whenLoaded('item'))
        ];
    }
    

    item 键仅在关系已加载时才会出现。

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 2019-10-20
      • 2021-11-18
      • 1970-01-01
      • 2018-11-30
      • 2022-01-01
      • 2017-05-06
      相关资源
      最近更新 更多