/
chieforik
/
AgroPro
Обзор
Документация
Войти
/
chieforik
/
AgroPro
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
models/GigaChatMessage.php
125 строк
3 KB
Орловский Александр
Первый
25 сен 2025, 02:26
25 сен 2025, 02:26
1567008
Код
Авторство
О чём код?
<?php namespace app\models; use Yii; use yii\behaviors\TimestampBehavior; use yii\db\ActiveRecord; /** * @property int $id * @property string $user_message * @property string|null $ai_response * @property int|null $user_id * @property string|null $session_id * @property int $created_at * @property int $updated_at */ class GigaChatMessage extends ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return '{{%gigachat_messages}}'; } /** * {@inheritdoc} */ public function behaviors() { return [ TimestampBehavior::class, ]; } /** * {@inheritdoc} */ public function rules() { return [ [['user_message'], 'required'], [['user_message', 'ai_response'], 'string'], [['user_id', 'created_at', 'updated_at'], 'integer'], [['session_id'], 'string', 'max' => 32], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'user_message' => 'Сообщение пользователя', 'ai_response' => 'Ответ AI', 'user_id' => 'Пользователь', 'session_id' => 'ID сессии', 'created_at' => 'Создано', 'updated_at' => 'Обновлено', ]; } /** * Сохранение сообщения в базу */ public static function saveMessage($userMessage, $aiResponse, $sessionId = null) { $message = new static(); $message->user_message = $userMessage; $message->ai_response = $aiResponse; $message->session_id = $sessionId ?: self::generateSessionId(); // Если пользователь авторизован, сохраняем его ID if (!Yii::$app->user->isGuest) { $message->user_id = Yii::$app->user->id; } return $message->save(); } /** * Генерация ID сессии */ public static function generateSessionId() { return substr(md5(uniqid('', true)), 0, 16); } /** * Получение истории переписки по сессии */ public static function getChatHistory($sessionId, $limit = 20) { return static::find() ->where(['session_id' => $sessionId]) ->orderBy(['created_at' => SORT_ASC]) ->limit($limit) ->all(); } /** * Получение последних сессий пользователя */ public static function getUserSessions($userId = null, $limit = 10) { $query = static::find() ->select(['session_id', 'MAX(created_at) as updated_at']) ->groupBy(['session_id']) ->orderBy(['updated_at' => SORT_DESC]) ->limit($limit); if ($userId) { $query->where(['user_id' => $userId]); } elseif (!Yii::$app->user->isGuest) { $query->where(['user_id' => Yii::$app->user->id]); } return $query->all(); } }