2017-07-25 37 views
-1

我嘗試不同之前,但不知何故,我的查詢將不會選擇最後一條評論。他總是選擇最古老的評論。然後我用groupBy而不是獨特的方式嘗試過。但是這也行不通。Laravel查詢不想選擇最後一個

我當前的查詢:

\App\Comment::limit(5)->groupBy('comments.id') 
      ->orderBy('comments.id', 'desc') 
      ->join('topics', 'comments.topic_id', '=', 'comments.id') 
      ->select('comments.user_id', 'topics.id', 'topics.name') 
      ->whereIn('topics.cat_id', $cats) 
      ->where([['comments.removed', '=', false],['topics.removed', '=', false]]) 
      ->get(); 

這是相當長的。 有人可以解釋爲什麼這不起作用。

+2

什麼你想達到什麼目的? – avonnadozie

+0

@avonnadozie抱歉,不好解釋我想根據最後的評論選擇5個主題。 – Smokegun

+0

無需等待我想選擇主題未刪除且處於所選類別中的最後評論 – Smokegun

回答

1

錯誤迄今發現不需要

  1. GROUPBY
  2. 你的連接語句join('topics', 'comments.topic_id', '=', 'comments.id')應在表commentstopics

修復

\App\Comment::select('comments.user_id', 'topics.id', 'topics.name') 
    ->join('topics', 'comments.topic_id', 'topics.id') 
    ->whereIn('topics.cat_id', $cats) 
    ->where('comments.removed', false) 
    ->where('topics.removed', false) 
    ->latest('comments.id') 
    ->limit(5) 
    ->get(); 

PS連接列: latest('comments.id')是非常方便的orderBy('comments.id', 'desc')

UPDATE

要獲得最多5個最近更新的主題的最新評論,試試這個

\App\Comment::select('comments.user_id', 'topics.id', 'topics.name') 
    ->from(DB::raw("(select * from comments where removed = 0 order by id desc) as comments")) 
    ->join('topics', 'comments.topic_id', 'topics.id') 
    ->whereIn('topics.cat_id', $cats) 
    ->where('topics.removed', false) 
    ->groupBy('topics.id') 
    ->limit(5) 
    ->get(); 
+0

這個解決方案看起來很乾淨,但是如果這兩個都是1它也需要filtert評論。topic_id – Smokegun

+0

如果你想只返回一個評論每個主題,然後由'topics.id'分組 – avonnadozie

+0

然後,那個問題回來了,然後我得到最古老的評論,而不是最新的評論。 – Smokegun

0

嘗試使用whereHas。你應該做這樣的事情:

\App\Comment::where('removed', false) 
      ->whereHas('topic', function($q) use ($cats) { 
       $q->where('removed', false) 
        ->whereIn('cat_id', $cats); 
      }) 
      ->limit(5) 
      ->orderBy('id', 'desc')->get(); 

要做到這一點,你必須具有的功能建立的關係,如topics:在Comment模型(即的hasMany)。

+0

調用未定義的方法Illuminate \ Database \ Query \ Builder :: topics()關係是否存在commet有一個屬於主題,主題有hasmany註釋 – Smokegun

+0

如果註釋屬於主題,只能嘗試'whereHas('topic',function ($ q){'。 – Laerte

+0

whereIn('topics.cat_id',$ cats)topics.cat_id doesn; t因爲連接isn而存在; t使用並且如果我添加whereIn到$ q它不能到達變量$貓? – Smokegun