背景
出发点是为了减少一次性查询的数据量,做了一个while循环,然后当不符合条件的时候,把while循环break掉
错误的做法
$openIds = $this->getUnionIdByOpenId();
\Log::info(json_encode($openIds));
while ($openIds != null){
$app = app('wechat.official_account');
$users = $app->user->select($openIds);
$list = [];
foreach ($users["user_info_list"] as $user){
$list[] = [
'open_id' => $user['openid'],
'union_id' => $user['unionid'],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
];
}
\DB::table('official_account')->insert($list);
$this->insertAccount();
}
- 在while里头写递归,是不会生效的,while会一直执行里头的循环体,且上述代码并不会break掉while的循环,因此会不断的执行写库的操作
正确的做法
public function insertAccount(){
while (1){
$openIds = $this->getUnionIdByOpenId();
\Log::info(json_encode($openIds));
if (count($openIds) > 0){
$app = app('wechat.official_account');
$users = $app->user->select($openIds);
$list = [];
foreach ($users["user_info_list"] as $user){
$list[] = [
'open_id' => $user['openid'],
'union_id' => $user['unionid'],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
];
}
\DB::table('official_account')->insert($list);
}else{
break;
}
}
echo "执行完毕";
return;
}
- 正确的操作应该如上面这段代码,在循环体内做判断,并在合适的时候讲循环break掉