首页 > 解决方案 > 如何从集合结果数组中排除关系列-急切加载

问题描述

我试图弄清楚如何在急切的负载收集结果数组中排除/隐藏关系列

我有 2 个模型,这是关系

产品.php

class Product extends Model
    {
        public function Category()
        {
            return $this->belongsTo(Category::class);
        }
    }

分类.php

class Category extends Model
    {
        public function Product()
        {
            return $this->hasMany(Product::class);
        }
    }

表字段

类别身份证,姓名

产品:id、名称、 category_id

所以,这是我的查询

$result = Product::leftJoin('product_tags', 'product.id', 'product_tags.product_id')
        ->with(['category' => function ($q) {
            $q->selectRaw('id,name as category_name');
        }])
        ->select('product.id', 'product.name','product.category_id',DB::raw('group_concat(DISTINCT(product_tags.product_tag)) as product_tag'))
        ->groupBy('product_tags.product_id')
        ->paginate($limit)
        ->toArray();

这是回应

{
    "id": 50,
    "name": "three",
    "category_id": 2, // this field I need to exclude from result array
    "product_tag": "123,3",
    "category": {
        "id": 2,
        "category_name": "Azo"
    }
}

以下是我要排除的回复

{
    "id": 50,
    "name": "three",
    "product_tag": "123,3",
    "category": {
        "id": 2,
        "category_name": "Azo"
    }
}

我试过这样做:

1.

$result['data'] = collect($result['data'])->except(['category_id']);
  1. $result['data'] = collect($result)->transform(function($i) { unset($i->category_id); return $i; });

即使我尝试使用except()辅助功能,但似乎所有的努力都毫无意义

注意:我知道我可以在模型中设置受保护的属性($hidden 或 $visible),我可能想在不同的上下文中使用它并想使用 laravel 的默认分页。

是否有可能以及这样做的任何方式?

非常感谢。

标签: phpmodellaravel-8eager-loading

解决方案


在第一次尝试时,每个孩子都会有category_id,而不是主数组。

collect($result)->map(function($item) {
    return collect($item)->except('category_id');
})->toArray();

在第二个中,您toArray()在主数组中使用,因此要取消设置category_id,您需要使用[]

unset($i['category_id']);

PS:我看到paginate()这是端点的结果?在这种情况下,您可以查看API Resource


推荐阅读