66b61eada4
- 创建 support/Db.php 和 support/Model.php - 在 bootstrap.php 中自动初始化数据库 - 移除 app/util/Db.php - 更新所有模型和控制器使用官方类 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
78 lines
1.7 KiB
PHP
78 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace support;
|
|
|
|
use Illuminate\Database\Capsule\Manager as Capsule;
|
|
|
|
class Db
|
|
{
|
|
/**
|
|
* @var Capsule
|
|
*/
|
|
protected static $capsule = null;
|
|
|
|
/**
|
|
* 初始化
|
|
*/
|
|
public static function init(): void
|
|
{
|
|
if (self::$capsule !== null) {
|
|
return;
|
|
}
|
|
|
|
$config = config('database');
|
|
$connections = $config['connections'] ?? [];
|
|
|
|
self::$capsule = new Capsule();
|
|
|
|
foreach ($connections as $name => $connection) {
|
|
self::$capsule->addConnection($connection, $name);
|
|
}
|
|
|
|
self::$capsule->setAsGlobal();
|
|
self::$capsule->bootEloquent();
|
|
|
|
if ($default = $config['default'] ?? null) {
|
|
self::$capsule->getDatabaseManager()->setDefaultConnection($default);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取连接
|
|
*/
|
|
public static function connection(?string $name = null): \Illuminate\Database\Connection
|
|
{
|
|
if (self::$capsule === null) {
|
|
self::init();
|
|
}
|
|
return self::$capsule->connection($name);
|
|
}
|
|
|
|
/**
|
|
* 获取表查询构造器
|
|
*/
|
|
public static function table(string $table, ?string $connection = null): \Illuminate\Database\Query\Builder
|
|
{
|
|
return self::connection($connection)->table($table);
|
|
}
|
|
|
|
/**
|
|
* 原始SQL表达式
|
|
*/
|
|
public static function raw(string $value): \Illuminate\Database\Query\Expression
|
|
{
|
|
return self::connection()->raw($value);
|
|
}
|
|
|
|
/**
|
|
* 获取 Capsule 实例
|
|
*/
|
|
public static function getCapsule(): Capsule
|
|
{
|
|
if (self::$capsule === null) {
|
|
self::init();
|
|
}
|
|
return self::$capsule;
|
|
}
|
|
}
|