setName('deleterepeatcustomer') ->addArgument('root_id', Argument::OPTIONAL, '组织根id') ->setDescription('the deleterepeatcustomer command'); } protected function execute(Input $input, Output $output) { $root_id = trim($input->getArgument('root_id')); $root = Org::find($root_id); if (empty($root)) { $output->writeln('根组织不存在'); return; } $orgIdList = Org::where([['path', 'like', $root->path . '%']])->column('id'); // 查询电话号码重复的数据 $rs = Customer::where([['org_id', 'in', $orgIdList]])->group('phone')->having('count(id)>1')->column('phone'); foreach ($rs as $v) { // 查询该电话号码中最新的一条数据id $idList = Customer::where([['org_id', 'in', $orgIdList], ['phone', '=', $v]])->column('id'); // 1)从追踪记录中查找最新的记录 $newCustomerId = CustomerVisitLog::where([['customer_id', 'in', $idList]])->order('addtime desc')->value('customer_id'); if (empty($newCustomerId)) { $newCustomerId = Customer::where([['org_id', 'in', $orgIdList], ['phone', '=', $v]])->order('last_contact_date desc, updatetime desc, addtime desc')->value('id'); } // 剔除多余数据 $newKey = array_search($newCustomerId, $idList); unset($idList[$newKey]); // 删除多余数据 Customer::where([['id', 'in', $idList]])->delete(); $output->writeln($v.'删除:'.count($idList).'条'); // 删除客户追踪记录 CustomerVisitLog::where([['customer_id', 'in', $idList]])->delete(); // 删除客户置顶 CustomerTop::where([['customer_id', 'in', $idList]])->delete(); // 预约记录 CustomersSubscribe::where([['customer_id', 'in', $idList]])->delete(); } // 指令输出 $output->writeln('ok'); } }