Files
wh-api/app/Utils/TableUtils.php
ykxiao 0b2299c427
Some checks failed
Build Docker / build (push) Has been cancelled
协程版仓库后端项目
2025-07-08 14:59:47 +08:00

81 lines
2.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Author: ykxiao
* Date: 2025/5/6
* Time: 下午10:42
* Description:
*
* (c) ykxiao <yk_9001@hotmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
declare(strict_types=1);
namespace App\Utils;
use App\Exception\ApiException;
use App\Model\Model;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\InvalidArgumentException;
/**
* Author: ykxiao
* Date: 2025/5/6
* Time: 下午10:44
* Description: 表工具类, 用于判断表是否存在某个字段
*
* (c) ykxiao <yk_9001@hotmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
trait TableUtils
{
/**
* 检查数据表是否包含指定列。
*
* @param Model|string $modelOrTable
* @param string $column 列名称。
* @return bool 如果数据表包含指定列,则返回 true否则返回 false。
*/
public static function hasColumn(Model|string $modelOrTable, string $column): bool
{
try {
if ($modelOrTable instanceof Model) {
$connection = $modelOrTable->getConnection();
$tableName = $modelOrTable->getTable();
} else {
// 如果是字符串表名,默认使用全局连接
$connection = Db::connection();
$tableName = $modelOrTable;
}
// 获取前缀(手动拼接)
$prefix = $connection->getConfig('prefix') ?? '';
$fullTable = $prefix . $tableName;
// 使用缓存避免频繁查询
$cacheKey = "table_column_exists:$fullTable:$column";
/** @var CacheInterface $cache */
$cache = ApplicationContext::getContainer()->get(CacheInterface::class);
if (($exists = $cache->get($cacheKey)) !== null) {
return $exists;
}
// 执行 SHOW COLUMNS
$result = $connection->select("SHOW COLUMNS FROM `$fullTable` LIKE '" . addslashes($column) . "'");
$exists = !empty($result);
$cache->set($cacheKey, $exists, 3600);
return $exists;
} catch (ContainerExceptionInterface|NotFoundExceptionInterface|InvalidArgumentException $e) {
throw new ApiException($e->getMessage());
}
}
}