laravel 中对模型关联计数

 

 

    文章列表页 评论数

        $post = App\Post::withCount('comments')->get(); 模型关联计数 
        
        {{$post->comments_count}}
        

    public function getArticleList()
    {
        
        $articles = Article::orderBy('created_at' , 'desc')->withCount('comments')->paginate(3);
        return view('article/articleList',compact('articles'));   
    }
    
    blade 模板中使用 withCount出来的结果
       @foreach( $articles as $article )
        <div class="blog-post">
            <h2 class="blog-post-title"><a href="/article_content/{{$article->id}}" >{{$article->title}}</a></h2>
            <p class="blog-post-meta">{{ $article->updated_at->toFormattedDateString() }} <a href="/user/5">{{$article->user->name}}</a></p>

            <p>  {!!str_limit($article->content , 200,'...')!!}
            <p class="blog-post-meta">赞 0  | 评论 {{$article->comments_count}}</p>
        </div>
         @endforeach

    

 

posted @ 2017-08-22 12:38  silvercell  阅读(3199)  评论(0)    收藏  举报