Laravel Count里面有刀片

时间:2015-06-01 01:06:50

标签: php laravel laravel-5

我正在尝试获取用户的总评论..

控制器:

public function index()
{
    $setting = Setting::findOrFail(1);

    $comments = Comment::where('published', '=', '1')->get();

    $users = User::all();

    return view('page.index', compact('setting', 'comments', 'users'));
}

查看:

@foreach($comments as $comment)

{{ count($users->where('user_id', '=', $comment->user_id)) }}

@endforeach

问题是它只返回0并且我有2条评论..即使使用用户ID代替“$ comment-> user_id”它也不起作用。仍显示0。

2 个答案:

答案 0 :(得分:5)

$users是一个集合,而不是一个查询。这样对待:

@foreach ($comments as $comment)

    {{ $users->where('user_id', $comment->user_id)->count() }}

@endforeach

该集合where方法not take an operator

根据你问题中的措辞,你似乎真的想要它反过来:

$comments = Comment::wherePublished(1)->get()->groupBy('user_id');

然后在你看来:

@foreach ($users as $user)

    {{ $comments->has($user->id) ? count($comments[$user->id]) : 0 }}

@endforeach

答案 1 :(得分:1)

我迟到了回答您的问题,Joseph已经向您展示了问题,但您也可能采取不同的方式。您可以使用Collection::groupBy对评论进行分组,例如:

$comments = Comment::all()->groupBy('user_id');

然后在view中,你可以试试这个:

@foreach($comments as $user => $userComments)
     // count($userComments)
     // Or
     @foreach($userComments as $comment)
      // {{ $comment->title }}
     @endforeach
@endforeach

在第一个循环(@foreach($comments as $user => $userComments))中,$useruser_id,它的值将是此用户的所有注释(数组),但是在组中。