企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[danger] withCount() 关联数量统计 应用场景: 不需要获取关联数据,只需要关联数据的统计 >[danger] 使用示例 ![](https://img.kancloud.cn/aa/c5/aac573db257b2bfeb5568cdc7d465577_415x251.png) ```php <?php namespace app\model; /** * 文章模型 */ class Article extends \think\Model { public function test() { // self::withCount('关联方法名')->select(); // self::withCount(['关联方法名' => '自定义属性名'])->select(); $data = self::withCount(['comments' => 'comm_count'])->select(); // 查看数据 dump($data->toArray()); } /** * 一对多关联 文章关联多个评论 */ public function comments() { return $this->hasMany(Comments::class, 'aid'); } } ``` >[danger] `关联预载入`和`关联统计`同时使用 ![](https://img.kancloud.cn/a6/8b/a68b7c1488b92a1e3a54a09879acb303_663x573.png) ~~~ $data = self::with('comments') ->withCount(['comments' => 'comm_count']) ->select(); ~~~ >[danger] 关联统计属性名 关联统计会自动添加一个以`关联方法名` + `_count` 为名称的属性保存到模型数据对象中 >[danger] 查询多个统计字段 ~~~ // 统计一个关联数据 $data = self::withCount('comments')->select(); // 统计多个关联数据 $data = self::withCount(['comments', 'likes'])->select(); ~~~ >[danger] 使用闭包的方式对关联统计进行条件过滤 ~~~ $data = self::withCount(['comments' => function($query) { // comments评论表id大于3 $query->where('id', '>', 3); // 没有使用闭包时 自定义关联统计属性名 // withCount(['关联方法' => '自定义属性名']) // 官方手册: 使用了闭包方式 自定义属性名的方法如下 // 但是测试结果 定义属性名无效 $alias = 'comm_count'; }, 'likes'])->select(); ~~~ >[danger] 所有的关联统计方法都可以多次调用 ~~~ $data = self::withCount('comments') ->withCount('likes') ->select(); ~~~