php - 如何从集合结果数组中排除关系列-急切加载
问题描述
我试图弄清楚如何在急切的负载收集结果数组中排除/隐藏关系列
我有 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']);
- $result['data'] = collect($result)->transform(function($i) { unset($i->category_id); return $i; });
即使我尝试使用except()
辅助功能,但似乎所有的努力都毫无意义
注意:我知道我可以在模型中设置受保护的属性($hidden 或 $visible),我可能想在不同的上下文中使用它并想使用 laravel 的默认分页。
是否有可能以及这样做的任何方式?
非常感谢。
解决方案
在第一次尝试时,每个孩子都会有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。
推荐阅读
- javascript - 单击时按钮不执行功能
- prolog - swi-Prolog 的程序语义:无法理解生成的替换
- ios - 在“for in loop”中使用延迟 DispatchQueue
- azure-devops - Azure Devops - 批量关联自动化测试用例到故事
- javascript - material-ui 'createSvgIcon' 不是从 '@material-ui/core/utils' 导出的
- ruby - Ruby 文字数组语法是方法调用吗?
- java - 使用 DynamoDBMapper 手动分页?
- python - 我只是想找出列表的最大值与列表中的其他元素之间的索引差异
- javascript - 在 ZF3 MVC 应用程序中使用 webpack 打包前端 JS 文件
- r - R中带有因变量的小提琴散点图