首頁  >  問答  >  主體

laravel 模型防止延遲載入在資源中使用「whenLoaded()」關係時拋出異常

我最近開始使用 Model::preventLazyLoading() 但即使關係未加載但有時可能會加載,它實際上也會引發錯誤

像資源 'discount' => $this->whenLoaded('meta', $this->meta->discount ?? 0),

#

laravel版本:9.17.0

#
P粉614840363P粉614840363262 天前379

全部回覆(1)我來回復

  • P粉920835423

    P粉9208354232024-01-06 11:06:13

    PHP 在此解析您的語法。無論如何,它都必須載入$this->meta,因為當PHP 解析您的程式碼時,它優先於whenLoaded() 方法.

    $this->whenLoaded('meta', $this->meta->discount ?? 0)

    這就是為什麼 whenLoaded() 可以採用 closure() 來避免載入關係,除非它們實際上已載入。此方法將在滿足 whenLoaded() 條件後首先評估閉包。

    $this->whenLoaded('meta', function () { return $this->meta->discount ?? 0; });

    回覆
    0
  • 取消回覆