我有一个Laravel产品模型,它有一个叫做细节的关系。我想把这两个雄辩的结果的特点结合在一起。
我的$product属性如下:
#attributes: array:7 [▼
"id" => 1
"title" => "test"
"slug" => "test"
"html" => null
"published_at" => "2022-01-27 11:01:00"
"created_at" => "2022-01-27 11:04:15"
"updated_at" => "2022-01-27 11:05:30"
]
此外,$product->details属性如下所示:
#attributes: array:6 [▼
"id" => 1
"model" => "test"
"sku" => "test"
"base_price" => null
"created_at" => "2022-01-27 11:04:15"
"updated_at" => "2022-01-27 11:05:30"
]
我需要的是这个结果:
#attributes: array:10 [▼
"id" => 1
"title" => "test"
"slug" => "test"
"html" => null
"model" => "test"
"sku" => "test"
"base_price" => null
"published_at" => "2022-01-27 11:01:00"
"created_at" => "2022-01-27 11:04:15"
"updated_at" => "2022-01-27 11:05:30"
]
请注意,这些都是雄辩的结果,并不是一个简单的数组。
发布于 2022-01-27 14:03:02
您可以使用API资源类进行格式化,也可以根据项目/首选项使用map()
函数。API资源可能如下所示:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'html' => $this->html,
"model" => $this->details?->model,
"sku" => $this->details?->sku,
"base_price" => $this->details?->base_price,
...
];
}
}
https://stackoverflow.com/questions/70877825
复制相似问题