MigrateMpUserPhone.php 1.81 KB
<?php
declare(strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use Throwable;

/**
 * 为 dc_mp_user 增加 phone、pwd_hash(手机号注册登录)
 */
class MigrateMpUserPhone extends Command
{
    protected function configure(): void
    {
        $this->setName('migrate:mp-phone')
            ->setDescription('Add phone & pwd_hash columns to mp_user table (run once)');
    }

    protected function execute(Input $input, Output $output): int
    {
        $conn  = (string) config('database.default');
        $cfg   = config('database.connections.' . $conn);
        $prefix = (string) ($cfg['prefix'] ?? '');
        $table  = $prefix . 'mp_user';

        try {
            $cols = Db::query('SHOW COLUMNS FROM `' . $table . "` LIKE 'phone'");
            if (!empty($cols)) {
                $output->writeln('<info>Column phone already exists on ' . $table . ', skipped.</info>');

                return 0;
            }
        } catch (Throwable $e) {
            $output->writeln('<error>' . $e->getMessage() . '</error>');

            return 1;
        }

        $sql = <<<SQL
ALTER TABLE `{$table}`
  ADD COLUMN `phone` varchar(20) DEFAULT NULL COMMENT '手机号账号' AFTER `gender`,
  ADD COLUMN `pwd_hash` varchar(255) NOT NULL DEFAULT '' COMMENT '手机号登录密码 bcrypt' AFTER `phone`,
  ADD UNIQUE KEY `uk_phone` (`phone`)
SQL;

        try {
            Db::execute($sql);
            $output->writeln('<info>OK: phone & pwd_hash added to ' . $table . '</info>');
        } catch (Throwable $e) {
            $output->writeln('<error>' . $e->getMessage() . '</error>');
            $output->writeln('You can also run SQL manually: database/patch_mp_user_phone.sql');

            return 1;
        }

        return 0;
    }
}