Laravel 8 條件關(guān)聯(lián)

2021-07-19 11:46 更新

除了有條件地添加屬性之外,你還可以根據(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ā)送給客戶端之前被刪除。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)