• laravel5.3之后可以使用withCount()这个方法


    比如:文章控制器ArticleController.php查询文章列表数据的时候用withCount连接Comment,Zan模型直接统计每篇文章的评论和点赞数量。
    
    使用之前需要在文章模型文件Article.php中建立与评论和赞模型的关联关系,且方法名字和withCount里面填写的一样。 
    Article.php模型中定义comments方法用调用hasMany和Comment建立模型一对多关系
        public function comments(){
            return $this->hasMany(Comment::class, 'art_id', 'id')->orderBy('created_at', 'desc');
        }
    Article.php模型中定义zans方法调用hasMany和Zan建立模型一对多关系
        public function zans(){
            return $this->hasMany(Zan::class, 'art_id', 'id')->orderBy('created_at', 'desc');
        }
    ArticleController.php控制器中分页查询文章列表,就可以把模型中定义关联关系的方法名字数组形式传入withCount()里面
    $articles = Article::orderBy('created_at', 'desc')->withCount(["comments","zans"])->paginate(10); 
    模板中:遍历的时候调用关联方法名字加_count组合的字段显示出统计结果 :{{$art->xxx_count}}
    @foreach ($articles as $key=>$art)
        <div class="blog-post">
           <h2 class="blog-post-title"><a href="/article/{{$art->id}}">{{$art->title}}</a></h2>
           <p class="blog-post-meta">{{$art->created_at}}<a href="/user/5"> by {{$art->user->name}}</a></p> {!! str_limit($art->content, 200, '....') !!}
           <p class="blog-post-meta">赞{{$art->zans_count}} | 评论 {{$art->comments_count}}</p>
       </div>
    @endforeach
  • 相关阅读:
    00005-js 获取uuid
    00004-form 表单的清空、重置 (jquery)
    使用Socket进行通信
    使用ServerSocket创建TCP服务器端
    TCP协议基础
    基于TCP协议的网络通信
    3D MAX在立方体的使用
    应用纹理贴图
    使用OpenGL ES绘制3D图形
    GL10控制图形旋转
  • 原文地址:https://www.cnblogs.com/sgm4231/p/10083009.html
Copyright © 2020-2023  润新知