美文网首页
thinkphp使用chunk笔记!

thinkphp使用chunk笔记!

作者: DragonersLi | 来源:发表于2021-09-25 15:58 被阅读0次

    chunk数据分批处理:

    处理大量数据库记录,可以考虑使用chunk方法,该方法一次获取结果集的一小块,然后填充每一小块数据到要处理的闭包,节省内存,直至处理全部完毕,返回结果。

    批量更新数据库用户表,更新为会员。每次取100条,结果赋值给$res,循环数据处理,直至数据库表中所有符合where条件的处理完毕!用浏览器执行代码会存在超时问题502 Bad Gateway

    tp5使用命令行chunk递归查询用户无限上级
    <?php
    namespace app\admin\command; 
    use think\console\{Input,Output,Command};
    use think\console\Input\{Option,Argument};
    use app\common\model\{User,UserUpper};
    class Up extends Command
    {
    
        //定义任务名和描述
        protected function configure(){
    
            $this->setName('up')->setDescription("php think up 用户上级关系"); //选项定义
        }
    
        //调用该类时,会自动运行execute方法
        protected function execute(Input $input, Output $output)
        {
            $time = time();
            try{
            User::where("1=1")
                ->field("id,mobile,upper,is_member")
                ->chunk(10, function($users) use($output,$time){
    
                    foreach ($users as $user) {
                        $pid = '';
                        if($user['id']){
                            $pid = self::digui($user['id']);
                            if(is_array($pid)){
                                $pid = implode(',',$pid);
                                $pid =  ','.$pid.',';
                            }
    
                        }
                        $insert[] = [
                            'uid'=>$user['id'],
                            'pid'=>$pid,
                            'create_time'=>$time,
                        ];
                    }
    
                    if(UserUpper::insertAll($insert)){
                        $output->writeln(" sync ok");
                    }else{
                        dlog('up','失败:'.$insert);
                    }
    
                },$field = 'id',$sort = 'asc');
            }catch (\Exception $e){
                $output->writeln($e->getMessage().';第'.$e->getLine());
            }
        }
    
    
        /**
         * 递归返回用户所有上级数组
         * @param int $id
         * @param array $result
         * @return array
         */
        protected static function digui($id = 0,&$result =[]){
    
            $pid = User::where(['id'=>$id])->value('upper');
    
            if($pid && $id !=$pid){
                $result[] = $pid;
               self::digui($pid,$result);
                return $result;
            }
        }
    
    }
    
    如果查询的数据表主键不是id,则需要指定字段$field,排序字段$sort

    [think\db\exception\PDOException] SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'order clause'

    相关文章

      网友评论

          本文标题:thinkphp使用chunk笔记!

          本文链接:https://www.haomeiwen.com/subject/xmpmrxtx.html