【问题标题】:Counting total posts by a user in the blade view在刀片视图中计算用户的帖子总数
【发布时间】:2018-07-21 03:31:24
【问题描述】:

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

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

从刀片视图中执行此操作是不好的做法吗?如果是这样,我将如何实现?

型号

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

【问题讨论】:

    标签: laravel-5 eloquent blade


    【解决方案1】:

    是的,这很糟糕。

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

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

    【讨论】:

    • 我的 post 表中有 user_id。我在哪里使用 $user->posts();
    【解决方案2】:

    简单的解决方案:

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

    刀片:

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

    【讨论】:

    • 这很糟糕,因为您在视图中查询!
    • @MahdiYounesi 好的。你说的对!这只是一个简单的解决方案。
    • 谢谢。这就是我想要的。我试图将它作为一种方法融入模型中,但我很挣扎。
    猜你喜欢
    • 2021-11-19
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2020-01-25
    相关资源
    最近更新 更多