情景:
我需要从与城市,邻居和类别有关系的表格属性中提取数据,将所有结果传递给将会“美化”#34;丑陋的专栏给好名字。
所以我选择使用方法WITH:
//Query example
$result = Property::query();
$result = $result()->select('somefields')
->with('city')
->with('neighborhood')
->with('category')
->paginate($limit);
//Lets get results and use collection to rename ugly columns name:
PropertyResource::collection($result);
//它将根据此解决方案重命名字段:https://laravel.com/docs/5.6/collections#method-toarray
我的问题是什么: PropertyResource仅重命名从表" Property"中检索的列。表"城市","类别"和"邻居"保留本机列名称。
如何通过其他集合传递$ result?
答案 0 :(得分:0)
在收集方法中,我可以这样重命名整个结果:
<?php
namespace App\Http\Resources\v1;
use Illuminate\Http\Resources\Json\Resource;
class Property extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->SOMEFIELD,
'featured' => $this->SOMEFIELD,
'superFeatured' => $this->SOMEFIELD,
//THIS ONE COMES FROM A RELATIONSHIP
'description' => $this->propertyAdvertisement->SOMEFIELD,
'saleValue' => $this->SOMEFIELD,
'saleFormOfPayment' => $this->SOMEFIELD,
'vacationRentValue' => $this->SOMEFIELD,
'annualRentValue' => $this->SOMEFIELD,
'dormitories' => $this->SOMEFIELD,
'suites' => $this->SOMEFIELD,
'wc' => $this->SOMEFIELD,
'parkingSpaces' => $this->SOMEFIELD,
'coverImage' => $this->SOMEFIELD,
'coverDescription' => $this->SOMEFIELD,
'coverOrder' => $this->SOMEFIELD,
'features' => $this->SOMEFIELD,
'category' => $this->SOMEFIELD,
'subcategory' => $this->SOMEFIELD,
'city' => $this->SOMEFIELD,
'condominium' => $this->SOMEFIELD,
'neighborhood' => $this->SOMEFIELD,
'ref' => $this->SOMEFIELD,
'privateArea' => $this->SOMEFIELD,
'totalArea' => $this->SOMEFIELD,
'terrainSize' => $this->SOMEFIELD,
'finances' => $this->SOMEFIELD,
'ownerParcels' => $this->SOMEFIELD
];
}
}
这样只有一个集合可以重命名整个结果。