79 lines
2.4 KiB
PHP
79 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Config\Database;
|
|
|
|
class Session
|
|
{
|
|
public static function findByUserId(int $userId): array
|
|
{
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare('SELECT * FROM sessions WHERE user_id = :user_id ORDER BY updated_at DESC');
|
|
$stmt->execute(['user_id' => $userId]);
|
|
return $stmt->fetchAll();
|
|
}
|
|
|
|
public static function findById(int $id): ?array
|
|
{
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare('SELECT * FROM sessions WHERE id = :id');
|
|
$stmt->execute(['id' => $id]);
|
|
$result = $stmt->fetch();
|
|
return $result ?: null;
|
|
}
|
|
|
|
public static function create(array $data): array
|
|
{
|
|
$db = Database::getInstance();
|
|
$stmt = $db->prepare('INSERT INTO sessions (user_id, name, provider, model, system_prompt, personality_id, thinking_mode) VALUES (:user_id, :name, :provider, :model, :system_prompt, :personality_id, :thinking_mode)');
|
|
$stmt->execute([
|
|
'user_id' => $data['user_id'],
|
|
'name' => $data['name'] ?? '新会话',
|
|
'provider' => $data['provider'] ?? 'newapi',
|
|
'model' => $data['model'] ?? 'gpt-3.5-turbo',
|
|
'system_prompt' => $data['system_prompt'] ?? '',
|
|
'personality_id' => $data['personality_id'] ?? null,
|
|
'thinking_mode' => $data['thinking_mode'] ?? 0,
|
|
]);
|
|
|
|
return self::findById((int) $db->lastInsertId());
|
|
}
|
|
|
|
public static function update(int $id, array $data): bool
|
|
{
|
|
$db = Database::getInstance();
|
|
|
|
$fields = [];
|
|
$params = ['id' => $id];
|
|
|
|
foreach ($data as $key => $value) {
|
|
$fields[] = "{$key} = :{$key}";
|
|
$params[$key] = $value;
|
|
}
|
|
|
|
$fields[] = 'updated_at = CURRENT_TIMESTAMP';
|
|
|
|
$sql = 'UPDATE sessions SET ' . implode(', ', $fields) . ' WHERE id = :id';
|
|
$stmt = $db->prepare($sql);
|
|
|
|
return $stmt->execute($params);
|
|
}
|
|
|
|
public static function delete(int $id): bool
|
|
{
|
|
$db = Database::getInstance();
|
|
|
|
$db->beginTransaction();
|
|
try {
|
|
$db->prepare('DELETE FROM messages WHERE session_id = :session_id')->execute(['session_id' => $id]);
|
|
$db->prepare('DELETE FROM sessions WHERE id = :id')->execute(['id' => $id]);
|
|
$db->commit();
|
|
return true;
|
|
} catch (\Throwable $e) {
|
|
$db->rollBack();
|
|
throw $e;
|
|
}
|
|
}
|
|
}
|