簡體   English   中英

Laravel Eloquent 中的預加載多態關系

[英]Eager loading polymorphic relations in Laravel Eloquent

我將rappasoft/laravel-authentication-log與我的User model 一起使用。它向用戶 model 公開了以下多態關系:

public function authentications()
{
    return $this->morphMany(AuthenticationLog::class, 'authenticatable')->latest('login_at');
}

現在,如果我運行$user->authentications->some_property$user來自User::get()集合),它會發出 N+1 個查詢。 我如何渴望加載這種關系?

我試過User::with('authentications')->get()但它似乎沒有用。 我仍然收到 N+1 個查詢。

好的,預加載似乎按原樣工作。 我正在使用顯式加載關系的$user->getLastLoginAt()方法:

    public function lastLoginAt()
{
    return optional($this->authentications()->first())->login_at;
}

我已將代碼更改為optional($this->authentications->first())->login_at並且我不再生成 N+1 查詢

暫無
暫無

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

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