2016-08-23 92 views
0

有許多分類(Category.php)在我的網站的索引,其中有許多委員會(Board.php)。 董事會可以有很多主題(Topic.php),並且主題可以有很多回復(Reply.php)。Laravel的hasMany關係計數

我想獲取當前董事會的回覆數,可能與預先加載。

我有一個辦法,但它執行了太多的查詢。我創建了一個post_count屬性,然後遍歷每個主題並收集多個回覆。有沒有辦法選擇當前主板的所有回覆?

public function getPostCountAttribute() 
{ 
    $count = 0; 
    foreach ($this->topics()->withCount('replies')->get() as $topic) { 
     $count += $topic->replies_count; 
    } 
    return $count; 
} 

回答

0

試試吧

變化

$count = 0; 
foreach ($this->topics()->withCount('replies')->get() as $topic) { 
    $count += $topic->replies_count; 
} 

$topic_ids = $this -> topics -> pluck('id'); 
$reply_count = Reply::whereIn('id',$topic_ids) -> count(); 
+0

不應該whereIn()有兩個參數?缺少參數2爲Illuminate \ Database \ Query \ Builder :: whereIn()..我改爲whereIn('topic_id',$ topic_ids),沒有結果。 – dinomuharemagic

+0

@core_m。我更新了。 – KmasterYC

+0

打印並查看$ topics_ids是否提取您的ID。代碼似乎沒有錯。 –

1

找到了一個不錯的方式。儘管如此,如果有人找到更好的方法來解決這個問題,我會留下這個問題。

我宣佈一個hasManyThrough關係,而所謂的計數():

Board.php:

public function replies() 
    { 
     return $this->hasManyThrough(Reply::class, Topic::class); 
    } 

然後叫:執行

$board->replies->count() 

30查詢(前45 )。

不過,我想找到一個熱心的方式來加載數據,得到的查詢數量下降到2次或3的查詢。

1

除了你reply,你可以做這樣的事情。

public function repliesCount() { 
     return $this->replies()->selectRaw('board_id, count(*) as aggregate') 
         ->groupBy('board_id'); 
    } 

,並使用該使用如下

$board->repliesCount() 

請注意,你必須根據你改變查詢。