在刀片视图中计算用户的总帖子数 [英] Counting total posts by a user in the blade view
本文介绍了在刀片视图中计算用户的总帖子数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已将博客中所有帖子的集合发送到索引视图,然后使用以下代码对每个用户发表的帖子总数进行计数.
I have sent a collection of all posts in my blog to my index view and then used the following code to count the total posts made by each user.
<p class="joined-text">Posts: {{count(App\Posts::where('user_id', $post->user->id)->get())}}</p>
在刀片视图中执行此操作是否是错误的做法?如果可以的话,我将如何实现?
Is this bad practice to do this from within the blade view? If it is how would I achieve this?
模型
class Posts extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comments::class, 'post_id');
}
}
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany('\App\Posts::class');
}
public function comments()
{
return $this->hasMany(Comments::class);
}
}
推荐答案
简单解决方案:
<p class="joined-text">Posts: {{ App\Posts::where('user_id', $post->user_id)->count() }}</p>
已更新
完整且更好的解决方案:
Complete and better solution:
Post.php
:
public function user(){
return $this->belongsTo(App\User::class);
}
User.php
:
public function posts(){
return $this->hasMany(App\Post::class);
}
public function getPostsCountAttribute(){
return $this->posts()->count();
}
刀片:
<p class="joined-text">Posts: {{ $post->user->posts_count }}</p>
这篇关于在刀片视图中计算用户的总帖子数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文