1

我有一个模型资源,我在其中调用$ this->tags

此资源返回如下:

"data": {
  "some_keys"  : ...,
  "some_keys2" : ...,
  "tags":[
           {
             "id": 1,
             "name": "c++",
             "parent_id": null,
             "type": null,
             "created_at": "2020-09-27 20:37:57",
             "updated_at": "2020-09-27 20:37:57",
             "pivot": {
                "task_id": 43,
                "skill_id": 1
             }
           }
        ]

我想做如下:

"data": {
  "some_keys"  : ...,
  "some_keys2" : ...,
  "tags": [
            {
              "id": 1,
              "name": "c++"
            }
          ]

我的资源模型:

public function toArray($request)
{
    $data = parent::toArray($request);
    $data["tags"] = $this->tags;
    return $data;
}

我的任务模型:

public function tags(){
    return $this->belongsToMany(Skill::class, 'task_skills', 'task_id', 'skill_id');
}

如何减少资源模型中的一些标签列?

我是这样解决的:

$data["tags"] = $this->tags->makeHidden(['pivot','created_at','updated_at','type','parent_id']);
4

1 回答 1

2

有很多收集方法,您正在尝试基于您可以使用的方法来实现。

采摘

$collection = collect([
    [
        'speakers' => [
            'first_day' => ['Rosa', 'Judith'],
            'second_day' => ['Angela', 'Kathleen'],
        ],
    ],
]);

$plucked = $collection->pluck('speakers.first_day');

$plucked->all();

// ['Rosa', 'Judith']

只要

$collection = collect(['product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false]);

$filtered = $collection->only(['product_id', 'name']);

$filtered->all();

// ['product_id' => 1, 'name' => 'Desk']

得到

$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$value = $collection->get('name');

// Taylor

如果你总是想隐藏一些属性,你可以使用

protected $hidden = ['parent_id', 'created_at'];在你的模型中

于 2020-09-27T22:13:10.687 回答