计算 blade 视图中用户的帖子总数

Counting total posts by a user in the blade view

我已将我博客中所有帖子的 collection 发送到我的索引视图,然后使用以下代码计算每个用户发布的帖子总数。

<p class="joined-text">Posts: {{count(App\Posts::where('user_id', $post->user->id)->get())}}</p>

从 blade 视图中执行此操作是一种不好的做法吗?如果是,我将如何实现?

型号

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);
    }
}

是的,这很糟糕。

如果 posts 中有 user_id 字段,您可以使用 relationships table

class User extends Model
{
  public function posts()
  {
     return $this->hasMany('App\Post');
  }
}

在控制器中

return view('sth')->with(['posts'=>$user->posts]);

然后在视图中

$posts->count();

或者,如果您不需要帖子,则只获取计数

$postCount = $user->posts()->count();

简单的解决方案:

<p class="joined-text">Posts: {{ App\Posts::where('user_id', $post->user_id)->count() }}</p>

已更新

完整且更好的解决方案:

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();
}

blade:

<p class="joined-text">Posts: {{ $post->user->posts_count }}</p>