【问题标题】:How can I do select some columns of a relation in the resources model?如何在资源模型中选择关系的某些列?
【发布时间】:2021-01-13 12:53:30
【问题描述】:

我有一个模型资源,我在其中调用 $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']);

【问题讨论】:

  • 如果我的回答没有解决你的问题,请让我详细了解你的问题,以便我为你提供帮助。
  • @PrafullaKumarSahu 我尝试了“仅”和“获取”,但其中的机器人没有解决我的问题。当我使用“仅”时,它返回空数组。对于get,它返回null。我也不想使用“采摘”
  • 所以你只需要标签和内部标签,你也只需要 id 和 name?
  • @PrafullaKumarSahu 不仅是标签,我只过滤返回 id 和 name 的标签。这是我需要修复的部分 $this->tags
  • 好的,我将更新我的答案,您能否编辑您的问题并添加您检索数据的方式,因为遍历集合会效率低下。

标签: php laravel eloquent laravel-8


【解决方案1】:

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

采摘

$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

如果你总是想保留一些属性hidden你可以使用

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

【讨论】:

  • 调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsToMany::all()
  • @Furkanozturk 你能在你的问题或要点中粘贴你收藏的副本并与我分享吗?
  • 我通过对其他列使用 makeHidden 来解决。感谢您的努力
  • @Furkanozturk 好的。
猜你喜欢
  • 2017-03-23
  • 2020-10-15
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多