2017-03-17 53 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 =不像>,首先你的代码分组您的文章并选择仅喜欢的文章。然后使用计数功能来计算数量,如邮政和新变量。用于紧凑方法传递该变量刀片文件