thinkphp 模型预载入减少查询次数 查询筛选 查询统计

模型预载入查询 筛选 统计

模型里
    public function profile()
    {

        return $this->hasMany(Profile::class);
    }


使用的地方 类里
  public function index()
    {
       // 普通查询 有多少条数据 foreach就会获取多少次 + 1次数据
       // $users = Users::select();
       // foreach ($users as $user) {
       //     echo $user->profile;
       // }

        // 预载入查询 只会查询两次表
        // ['profile'] 可以查询多个表
        //  $users = Users::with(['profile'])->select();
        //  foreach ($users as $user) {
            //   echo $user->profile;
        // json($user->profile);
        // }

        // 表里字段过多 可以自定义要 visible显示 或者 hidden隐藏 的字段
        // $users = Users::with(['profile'])->select();
        // profile.hobby profile是副表 hobby是副表里的字段 只显示副表的hobby字段
        // $users->visible(['id', 'profile.hobby']);
        // return json($users);


        // 统计
        // 关联统计 withCount 会自动统计出主表数据 对应的 关联副表的数据条数
        // $users = Users::withCount(['profile'])->select();
        // foreach ($users as $user) {
        //     echo $user->profile_count;
        // }

    }

posted on   完美前端  阅读(52)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示