W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
除了有條件地添加屬性之外,你還可以根據(jù)模型關(guān)聯(lián)是否已加載來(lái)有條件地在你的資源響應(yīng)中包含關(guān)聯(lián)。這允許你在控制器中決定加載哪些模型關(guān)聯(lián),這樣你的資源可以在模型關(guān)聯(lián)被加載后才添加它們。
這樣做可以避免在你的資源中出現(xiàn)「N+1」查詢問(wèn)題。你應(yīng)該使用 whenLoaded
方法來(lái)有條件的加載關(guān)聯(lián)。為了避免加載不必要的關(guān)聯(lián),此方法接受關(guān)聯(lián)的名稱而不是關(guān)聯(lián)本身作為其參數(shù):
/**
* 將資源轉(zhuǎn)換成數(shù)組
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'posts' => PostResource::collection($this->whenLoaded('posts')),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
在上面這個(gè)例子中,如果關(guān)聯(lián)沒(méi)有被加載,則 posts
鍵將會(huì)在資源響應(yīng)被發(fā)送給客戶端之前被刪除。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: