This commit is contained in:
81
app/Utils/TableUtils.php
Normal file
81
app/Utils/TableUtils.php
Normal file
@ -0,0 +1,81 @@
|
||||
<?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());
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user