2017-03-17 279 views
0

我希望每個帖子都能顯示其喜歡的總數。如何製作一個laravel像櫃檯?

我有這樣一個循環,我blade.php文件:

 @foreach ($posts as $post) 
      <article class="post" data-postid="{{ $post->id }}"> 
       <p>{{ $post->body }}</p> 
       <div class="info"> 
        Posted by {{ $post->user->first_name }} on {{ $post->created_at }} 
       </div> 
       <div class="interaction"> 
        {{ $countlike->where(['post_id' => $post->id])->get()->count() }}<a href="#" class="like"> {{ Auth::user()->likes()->where('post_id', $post->id)->first() ? Auth::user()->likes()->where('post_id', $post->id)->first()->like == 1 ? 'You Liked This Post' : 'Like' : 'Like' }}</a> | 
        {{ $countdislike->where(['post_id' => $post->id])->get()->count() }}<a href="#" class="like"> {{ Auth::user()->likes()->where('post_id', $post->id)->first() ? Auth::user()->likes()->where('post_id', $post->id)->first()->like == 0 ? 'You Disliked This Post' : 'Dislike' : 'Dislike' }}</a> | 
        @if(Auth::user() == $post->user) 
        <a href="#" class="edit">Edit Post</a> | 
        <a href="{{ route('post.delete', ['post_id' => $post->id]) }}">Delete</a> 
        @endif 
       </div> 
      </article> 
      <br> 

     @endforeach 

這是我的控制器功能:

public function getDashboard(Request $request) { 
    $posts = Post::orderBy('created_at', 'desc')->get(); 
    $countlike = Like::where(['like' => '1']); 
    $countdislike = Like::where(['like' => '0']); 
    return view('dashboard')->with(['posts' => $posts])->with(['countlike' => $countlike])->with(['countdislike' => $countdislike]); 
    } 

喜歡在數據庫: likes in the database

帖子在數據庫: posts in the database

結果: enter image description here

雖然循環中的第一篇文章與ORM進行通信,但其餘部分沒有。 我無法將雄辯的ORM集成到blade.php文件中的循環中,我在這裏做錯了什麼?

+0

你能用不同的詞來解釋你到底想要完成什麼嗎? – Peon

回答

1

問題

在該循環中,where函數這裏{{ $countlike->where(['post_id' => $post->id])->get()->count() }}將保持增加更多where條件下與同一個對象$countlike,同樣爲$countdislike這將最終返回任何在第一次循環後結果。

解決方案

一個更好的辦法讓喜歡計數每個職位將通過PostLike之間的一個一對多的關係,然後你就可以在迴路中接入這樣

$post->likes()->where(['like' => '1'])->count()對於喜歡

$post->likes()->where(['like' => '0'])->count()對於不喜歡

更新

正如Nickstery指出的那樣,避免在循環內進行數據庫查詢。使用with以便隨着帖子一起加載喜歡

//Get posts and likes with most recent posts on top 
$posts = Post::with('likes')->latest()->get(); 
//then in the loop 
$post->likes->where('like', 1)->count() //for likes 
$post->likes->where('like', 0)->count() //for dislikes 
1

從不在循環內部使用DB查詢。通過一個數據庫查詢獲取PHP中所需的數據並將其發送到查看。中郵 使用模型relations和喜歡 ,你會重寫喜歡

$postsWithLikes = Post::with('likes')->all(); 
View::share('posts', $postsWithLikes); 
return view('my_view'); 
+0

感謝您的評論,我會適應它。 –

0

兄弟,它很簡單

public function getDashboard(Request $request) { 
    $count = '1'; 
    $posts = Post::groupBy('post_id') 
        ->where('like',$count)->get(); 
    $like_count = count($post); 
    return view('dashboard', compact('like_count')); 
} 

現在做鞭打值1 =>狀或0 =不像>,首先你的代碼分組您的文章並選擇僅喜歡的文章。然後使用計數功能來計算數量,如郵政和新變量。用於緊湊方法傳遞該變量刀片文件