Files
datahub/backend/app/Command/AppCompanySync.php
T
2025-11-11 09:26:23 +08:00

71 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use App\Platform\Tools\Request\CompanyRequest;
use App\Model\Company;
use Hyperf\DbConnection\Db;
use App\Utils\Log;
use Exception;
#[Command]
class AppCompanySync extends HyperfCommand
{
public function __construct(protected ContainerInterface $container)
{
parent::__construct('app:company:sync');
}
public function configure()
{
parent::configure();
$this->setDescription('Sync companies from Tools Dashboard');
}
public function handle()
{
$companies = CompanyRequest::all();
try{
Db::beginTransaction();
$companies->each(function($el){
$exist_company = Company::find($el['id']);
if($exist_company){
# @attention update 方法不会进行 cast 类型转换,执行时需要注意
$exist_company->update([
'name' => $el['name'],
'enabled' => $el['isEnabled']
] );
return;
}
Company::create([
'id' => $el['id'],
'name' => $el['name'],
'enabled' => $el['isEnabled']
]);
});
Db::commit();
$this->info("公司数据同步已完成");
} catch(Exception $e){
Db::rollBack();
dump($e->getMessage());
Log::error($e->getMessage());
$this->error($e->getMessage());
$this->info("公司数据同步失败,数据更新已撤销");
}
}
}