协程版仓库后端项目
Some checks failed
Build Docker / build (push) Has been cancelled

This commit is contained in:
2025-07-08 14:59:47 +08:00
commit 0b2299c427
134 changed files with 19277 additions and 0 deletions

81
app/Utils/TableUtils.php Normal file
View 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());
}
}
}