簡體   English   中英

Laravel-渴望加載非關系方法(N + 1期)

[英]Laravel - Eager load a non-relationship method (N+1 issue)

隨着laravel的急切加載,我可以做類似的事情

$forums = Forum::with('posts', 'threads')->get();

無需做很多查詢就可以將其線程作為其帖子和論壇。

但是,我有一種方法可以獲取論壇的最新帖子。

這是我在Forum.php方法

public function lastThread()
{
    $forums = $this->arrayOfIDs(); // get array of all ids, even subforum's subforums.
    return Thread::whereIn('forum_id', $forums)->orderBy('updated_at', 'desc')->first();
}

這是我獲取最后一個線程的局部視圖:

@if ($subforum->lastThread())

    <a href="{{ viewThread($subforum->lastThread()) }}">
        {{ $subforum->lastThread()->title }}
    </a>
    <br>
    <a href="{{ viewPost($subforum->lastThread()->lastPost) }}"> {{ trans('forum/post.last_post') }}
        :</a>
    <a href="{{ viewProfile($subforum->lastThread()->lastPost->user) }}"> {{ $subforum->lastThread()->lastPost->user->info() }}</a>
    <br>
    {{ $subforum->lastThread()->lastPost->created_at }}

@endif

如您所見,如果我$subforum->lastThread()執行$subforum->lastThread() 我可以將其存儲在$lastThread = $subforum->lastThread()類的變量中,然后執行諸如$lastThread->created_at以減少查詢數量,但我認為將其包含在原始查詢中會容易得多獲得所有論壇。

像這樣: $forums = Forum::with('posts', 'threads', 'lastThread')->get(); 也許? 我已經嘗試為此方法創建hasOne關系,但這種方法不起作用,因為最后一個線程不一定屬於該特定子論壇。

無論如何,我怎樣才能最好地解決此N + 1問題?

謝謝。

您有無窮的選擇,

如果Cache類適合您,那么我也可以執行以下操作:

protectd $lastThread;

public function lastThread()
{
     if ($this->lastThread) return $this->lastThread;
     return $this->fetchLastThread();
}

    public function fetchLastThread() {
         $forums = $this->arrayOfIDs(); // get array of all ids, even subforum's subforums.
         $this->lastThread = Thread::whereIn('forum_id', $forums)->orderBy('updated_at', 'desc')->first();
         return  $this->lastThread;
}

暫無
暫無

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

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