有没有办法强制关系在 Lumen/Laravel 模型中按特定顺序加载?

问题描述 投票:0回答:1

我有一个 Lumen (8) 模型,其关系依赖于另一个关系。我希望能够做到以下几点,

    public function getThingId(): int
    {
        return $this->thing->id;
    }

    public function thing(): BelongsTo
    {
        return $this->belongsTo(Thing::class);
    }

    public function otherThing(): HasMany
    {
        return $this->hasMany(OtherThing::class, 'another_id')->where('thing_id', '=', $this->getThingId())->where(/* some more criteria */);
    }

这是行不通的。

$this->getThingId()
返回
null
关系中的
otherThings
。如果我使用
$this->thing->id
一切正常。不过,我更喜欢使用
$this->getThingId()

有没有办法强制 Laravel 在

thing
关系之前加载
otherThing
关系? (或者也许还有其他事情我没有注意到)。

php laravel lumen
1个回答
0
投票

您可以使用 load 方法在访问 getThingId() 之前强制预先加载事物关系。以下是修改 otherThing 关系以确保事物关系已加载的方法:

public function otherThing(): HasMany

{ $this->load('东西'); // 立即加载“事物”关系

return $this->hasMany(OtherThing::class, 'another_id')->where('thing_id', '=', $this->getThingId())->where(/* some more criteria */);

}

© www.soinside.com 2019 - 2024. All rights reserved.