簡體   English   中英

如何在 Laravel 中不需要時禁用關系加載

[英]How to disable loading of relationships when not needed in Laravel

是否可以禁用關系加載,但僅限於某些情況?

這是我的模型:

class League extends Model
{
    ...

    public function country()
    {
        return $this->belongsTo(Country::class)->with('translations');
    }
}

class Country extends Model
{
    ...

    public function translations()
    {
        return $this->hasMany(CountryTranslation::class, 'country_id');
    }
}

class CountryTranslation extends Model
{
    ...
}

在很多地方,我需要加載國家/地區的翻譯關系,但在某些頁面上,我只想顯示有關聯盟及其國家/地區的信息。 我不想在那里顯示 CountryTranslation 集合。

這是該頁面的代碼:

$country = $league->country;

是否只有這條線可以禁用關系?

因此,您目前正在找出不在關系內部定義急切加載的原因之一。 第一個建議是從關系定義中刪除with() ,並在需要的地方添加它。 如果需要,您可以創建另一個啟用預加載的關系,它可以使用基本關系來保持它的 DRY:

public function country()
{
    return $this->belongsTo(Country::class);
}

public function countryWithTranslations()
{
    return $this->country()->with('translations');
}

如果此代碼更改不可行,您將需要更改訪問國家/地區關系的方式。 當您訪問關系屬性時,它會延遲加載關系,您無法修改關系查詢。 因此,不是訪問關系屬性,而是需要調用關系查詢以便修改它。

因此,您將無法執行$country = $league->country; ,但你可以這樣做:

$country = $league->country()->without('translations')->first();

with()只是急切地加載翻譯以避免額外的查詢,但是你應該能夠在有和沒有它的情況下加載翻譯,沒有 with( 添加額外的查詢。https://laravel.com/docs/9.x/eloquent -關系#eager-loading

你會想要改變:

    public function country()
    {
        return $this->belongsTo(Country::class)->with('translations');
    }

    public function country()
    {
        return $this->belongsTo(Country::class);
    }

如果你想加載翻譯,你可以在控制器中完成

// if you want translations at some point do this:
$league = League::with('country.translations')
$country = $league->country->translations

// if you do not want translations
$league = League::with('country')
$country = $league->country;

如果您不想觸摸:

    public function country()
    {
        return $this->belongsTo(Country::class)->with('translations');
    }

你可以創建另一種方法

    public function countryClean()
    {
        return $this->belongsTo(Country::class);
    }

$country = $league->countryClean;

暫無
暫無

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

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