比如:文章控制器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

实例:

    $query = Inquiry::with(['invoices','user.user','prod.cate','company'])->withCount('quotation')->whereHas('user',function($q) use ($role_id,$user_id,$intermediary_id){
                    if($role_id == 3){
                        $q->where('user_id','=',$user_id);
                    }
                })->orderBy('id','desc');
                
    $res = $query->paginate($request->get('limit', 30))->toArray();
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res['data']
        ];
        return response()->json($data);
    <?php    
    namespace App\Models\Prod;
    use App\Models\Company\Company;
    use App\Models\Member\Member;
    use Illuminate\Database\Eloquent\Model;
    class Inquiry extends Model
    {
        public $guarded = [];
        protected $casts = ['package'=>'array'];
        protected $fillable =['prod_id','cas','prod_name','package','invoice_type','province','city','district','note','anonymous','allow_contact','user_id','user_name','status','handle','origin','company_name','company_id'];
        public function invoices(){
            return $this->hasOne(InvoiceCategory::class, 'id', 'invoice_type');
        }
        public function user(){
            return $this->hasOne(Member::class, 'id','user_id');
        }
        public function prod(){
            return $this->hasOne(Prod::class, 'cas','cas');
        }
        public function company(){
            return $this->hasOne(Company::class, 'id','company_id');
        }
        public function quotation(){
            return $this->hasMany(InquiryQuotation::class, 'inquire_id','id')->where('status','=',2);
        }
    }