繁体   English   中英

问题统计 laravel 中每个帖子的评论数 8

[英]issues counting number of comments of each post in laravel 8

我正在尝试使用 laravel eloquent 来实现计算 laravel 8 中单个帖子的评论数量。但我只是在刀片中没有得到任何空白值,

后 model

public function comments()
{
    return $this->hasMany('App\Models\Comment');
}

评论 model

public function post()
{
    return $this->belongsTo('App\Models\Post');
}

Controller

use App\Models\Post;
use App\Models\Comment;
use Illuminate\Database\Eloquent\Model;

public function index(Post $post)
{
    $counters = $post->withCount('comments')
                ->orderBy('created_at', 'desc');

    return view('app/blog', compact('counters'));
}

查看(刀片文件)

@foreach($counters as $counter)
    <p>Comments :$counter->comments_count</p>
@endforeach

首先,将刀片更改为 echo output。

@foreach($counters as $counter)
    <p>Comments: {{ $counter->comments_count }}</p>
@endforeach

然后将您的 controller 更改为

public function index(Post $post)
{
    $counters = Post::withCount('comments')
    ->orderBy('created_at', 'desc')
    ->get();

    return view('app/blog', compact('counters'));
}

您使用的withCount方法错误。 它旨在用于查询构建器,而不是单个 model。

此 controller 现在将返回所有帖子,然后将comments_count附加到每个帖子。 这似乎是你想要的。


我还在索引签名中留下了$post ,但这可能会被删除,因为看起来您的刀片想要所有帖子。

如果不是,则将 controller 更改为:

public function index(Post $post)
{
    $counters = Post::withCount('comments')
    ->where('id', $post->id)
    ->orderBy('created_at', 'desc')
    ->get();

    return view('app/blog', compact('counters'));
}

或者,也许您想要该帖子的所有评论,在这种情况下,请执行此操作。

public function index(Post $post)
{
    $counters = $post->comments()->count();
    return view('app/blog', compact('counters'));
}
<p>Comments: {{ $counters }}</p>

请注意,我在评论关系上使用了括号。 这是为了加快查询速度,因为它只会查询数据库的记录数,而不是获取所有数据,然后计算记录数。
此外,我从刀片中删除了 foreach,因为$counters现在只会返回 integer。

you don't have to do a query for this. Just do the following

**in controller**

 public function index(Post $post)

{
     $counters = count($post->comments);
    return view('app/blog', compact('counters'));
}
**and in view(blade file)**

<p>Comments :{{$counters }}</p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM