Laravel Count里面有刀片

Tia*_*goF 1 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'));
}
Run Code Online (Sandbox Code Playgroud)

视图:

@foreach($comments as $comment)

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

@endforeach
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*ber 5

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

@foreach ($comments as $comment)

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

@endforeach
Run Code Online (Sandbox Code Playgroud)

集合的where方法不需要操作员.


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

$comments = Comment::wherePublished(1)->get()->groupBy('user_id');
Run Code Online (Sandbox Code Playgroud)

然后在你看来:

@foreach ($users as $user)

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

@endforeach
Run Code Online (Sandbox Code Playgroud)