簡體   English   中英

Laravel-計算“線程”記錄中的記錄總數

[英]Laravel - count the total number of records in “threaded” records

考慮一個可以有很多子論壇的論壇,​​而這個子論壇可以有更多的子論壇。

我的forums表是這樣的:

idparent_idnameis_category

論壇類別( is_category )中不能包含主題。 但是,可以在forums表中使用parent_id作為id 這是我可以在論壇中放置子論壇的一種方式。 簡而言之,一個論壇可以有許多子論壇,而子論壇又可以有更多的子論壇,也可以有更多的子論壇,等等。

演示記錄:

| id | parent_id | name              | is_category |
|----|-----------|-------------------|-------------|
| 1  | 0         | Suggestions       | 1           |
| 2  | 1         | site suggestions  | 0           |
| 3  | 1         | forum suggestions | 0           |
| 4  | 2         | bugs              | 0           |

我的觀點:

@if ($forum->hasSubforum())
    @foreach ($forum->subforums as $subforum)
        {{ $subforum->name }}

        <h1>subforums</h1>
        @if ($forum->hasSubforum())
        @foreach ($subforum->subforums as $child)
            {{ $subforum->name }}
        @endforeach
        @endif
    @endforeach
@endif

我嘗試過的

$threads = 0;
while(!$forum->subforums->isEmpty()) {
    $threads += $forum->threads->count();
    while(!$forum->subforums->isEmpty()) {
        $threads += $forum->threads->count();
    }
}

這甚至不起作用... :(

TL; DR如您所見,我向用戶顯示子表單。 但是,如果我想顯示一個子論壇有多少個帖子,該怎么辦? 請注意,一個子論壇可以有更多的子論壇,從而可以有很多線程。 我不能簡單地執行$subforum->threads->count()因為那只會計算每個子論壇所擁有的線程。 我還想計算該子論壇的所有子級都有的線程數。

您可以通過遞歸來實現。

function countThreads($forum) {
    $count = $forum->threads->count();
    if ($forum->hasSubforum()) { {
        foreach ($forum->subforums as $subforum) {
            $count += countThreads($subforum);
        }
    }
    return $count;
}

暫無
暫無

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

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