我在我的模型中使用了關系,它作業正常,但輸出陣列的排序是錯誤的。我想移動created_at并updated_at放在陣列的末尾
輸出是:
{
"id": 1,
"title": "Test home",
"created_at": "2022-01-01T15:27:31.000000Z", <---------
"updated_at": "2022-01-01T15:27:31.000000Z", <---------
"doors": [
{
"id": 1,
"home_id": 1,
"button_count": 2,
"created_at": null,
"updated_at": null
}
]
}
但它應該是:
{
"id": 1,
"title": "Test home",
"doors": [
{
"id": 1,
"home_id": 1,
"button_count": 2,
"created_at": null,
"updated_at": null
}
],
"created_at": "2022-01-01T15:27:31.000000Z", <---------
"updated_at": "2022-01-01T15:27:31.000000Z" <---------
}
這是我的模型課:
class Home extends Model
{
use HasFactory;
protected $table = "homes";
protected $hidden = ["device_id"];
protected $with = ["doors"];
public function device(){
return $this->hasOne(Device::class,"id","device_id");
}
}
uj5u.com熱心網友回復:
如果您正在構建 API(不確定您的場景),最簡潔的方法是使用資源,您可以在其中根據需要格式化回應。這也有助于確保模型在所有端點中都以相同的結構回傳。
假設您想使用他們的設備獲取所有家庭,您可以創建一個DeviceResource用于回傳特定設備屬性
PHP artisan make:resource DeviceResource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class DeviceResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'home_id' => $this->home_id,
'button_count' => $this->button_count,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
}
然后創建一個HomeResource將包括DeviceResource
PHP artisan make:resource HomeResource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class HomeResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'devices' => DeviceResource::collection($this->whenLoaded('devices')),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
}
然后你只需HomeResource在你的控制器中回傳集合
$homes = Home::with('devices')->get();
$response = HomeResource::collection($homes);
return $response;
或者如果您只想回傳 1 Home...
$home = Home::with('devices')->findOrFail($home_id);
$response = new HomeResource($home);
return $response;
請注意,如果您不加載devices關系,HomeResource則不會回傳該devices屬性。
uj5u.com熱心網友回復:
您可以使用資源來映射資料并根據需要組織回應
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406105.html
標籤:
