繁体   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