如何使用 Laravel 中的關系輕松地重新格式化資料庫中的資料,一直在遍歷查詢的資料并重新格式化,因為我回圈然后推入一個陣列,然后在我將陣列作為 json 回傳之后,但隨著資料的增長,我發現了挑戰它完全變慢了。有沒有更好的方法來做到這一點。
uj5u.com熱心網友回復:
哦,我也有這個問題,但更好的解決方法是使用 laravel Eloquent API Resources 來使用此命令創建資源。
php artisan make:resource UserResource
然后在您可以重新格式化來自該資源的資料和關系之后,例如如下所示
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'patientName' => $this->patient_name,
'patientContact' => $this->patient_contact,
'patientEmail' => $this->patient_email,
'patientCode' => $this->patient_code,
'NIN' => $this->patient_nin,
'country' => $this->country,
'DOB' => $this->dateofbirth,
'patientAddress' => $this->patient_address,
'branch' => $this->whenLoaded('branch'),
'gender' => $this->gender,
'country_details' => $this->whenLoaded('cou'),
'status' => $this->p_status,
'visits' => $this->visits->count(),
'lastvisit' => $this->visits->max(),
'allvisits' => $this->visits,
'dateCreated' => Carbon::parse($this->created_at)->format('d/m/Y | h:i A'),
'dateUpdated' => Carbon::parse($this->updated_at)->format('d/m/Y | h:i A'),
];
}
有關更多資訊,請查看https://laravel.com/docs/8.x/eloquent-resources
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403664.html
標籤:
