簡體   English   中英

為 Laravel 關系返回 null 而不是“調用未定義的關系”錯誤

[英]Returning null instead of "Call to undefined relationship" error for Laravel relationships

當我ModelName::with('somerelation')->get()使用ModelName::with('somerelation')->get()時,如果模型沒有這種關系,我會Call to undefined relationship [somerelation] on model [App\\SomeModel]錯誤。

但是對於多態關系,我得到了所有相關模型的集合,我想使用with('somerelation')並在未定義關系時獲取null 有什么方法可以避免錯誤並從 with() 或有條件地使用 with 返回 null 嗎?

我在所有 Laravel 項目中所做的是創建一個擴展 Eloquent Model 的 Model 類,我的所有模型都將擴展我的 Model 類,因此我可以使用我的規則覆蓋 Eloquent Model 中的一些方法。

因此,您可以創建一個新類(我稱其為 Model)並使用 try/catch 塊重新調整 null 來覆蓋該方法,以防 eloquent 模型拋出此異常。

例子:

namespace App;

use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\RelationNotFoundException;

abstract class Model extends EloquentModel
{
    public static function with($relations)
    {
        try {
            return parent::with($relations);
        } catch (RelationNotFoundException $e) {
            return null;
        }
    }
}

@Leonardo Oberle 的先前回答對我不起作用。 我一直在努力尋找一種方法來驗證傳遞給with()方法的關系字符串的完整性,因此它只會在關系存在時加載關系,並且在缺少某些內容時不會拋出錯誤。

因此,我最終創建了一個抽象 Model 類,它從 EloquentModel 擴展而來,並覆蓋了Leonardo Oberle's響應中的with()方法。

唯一的事情是該方法的代碼應該如下所示:

namespace App;

use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\RelationNotFoundException;

abstract class Model extends EloquentModel
{
    public static function with($relations)
    {
        $filteredRelations = $this->relationExistsUntil($relations);

        parent::with($filteredRelations);

    }
}


    /**
     * @param string $with
     * @return string
     */
    protected function relationExistsUntil(string $with): string
    {
        $model = $this;
        $result = '';
        $relationParts = explode('.', $with);

        foreach ($relationParts as $relationPart) {
            $isValidRelation = method_exists($model, $relationPart) && $model->{$relationPart}() instanceof Relation;

            if (!$isValidRelation) {
                break;
            }

            $result .= empty($result) ? $relationPart : ".$relationPart";
            $model = ($model->{$relationPart}()->getRelated());
        }

        return $result;
    }



So, with that, if you will try smth like


`$user->with('relation1.relation2.relation3');`
where `relation2` doesn't exist, it will load only `relation1` and the rest will be skipped, and no exceptions/errors would be thrown.

Just don't forget to make all models then extend from that new abstract class.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM