From 13222fbe9a8f82ef045e0e22989208b5dda39f62 Mon Sep 17 00:00:00 2001 From: kuaifan Date: Fri, 6 Dec 2024 17:57:38 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96=E5=B7=B2=E8=AF=BB?= =?UTF-8?q?=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Models/WebSocketDialogMsg.php | 51 ++++++++++++++++++------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/app/Models/WebSocketDialogMsg.php b/app/Models/WebSocketDialogMsg.php index 72362a42b..394db75d9 100644 --- a/app/Models/WebSocketDialogMsg.php +++ b/app/Models/WebSocketDialogMsg.php @@ -112,7 +112,11 @@ class WebSocketDialogMsg extends AbstractModel public function getPercentageAttribute() { if (!isset($this->appendattrs['percentage'])) { - $this->generatePercentage(); + if ($this->read > $this->send || empty($this->send)) { + $this->appendattrs['percentage'] = 100; + } else { + $this->appendattrs['percentage'] = intval($this->read / $this->send * 100); + } } return $this->appendattrs['percentage']; } @@ -189,22 +193,6 @@ class WebSocketDialogMsg extends AbstractModel return $msg; } - /** - * 获取占比 - * @param bool|int $increment 是否新增阅读数 - * @return int - */ - public function generatePercentage($increment = false) { - if ($increment) { - $this->increment('read', is_bool($increment) ? 1 : $increment); - } - if ($this->read > $this->send || empty($this->send)) { - return $this->appendattrs['percentage'] = 100; - } else { - return $this->appendattrs['percentage'] = intval($this->read / $this->send * 100); - } - } - /** * 标记已送达 同时 告诉发送人已送达 * @param $userid @@ -234,16 +222,17 @@ class WebSocketDialogMsg extends AbstractModel if (!$msgRead->read_at) { $msgRead->read_at = Carbon::now(); $msgRead->save(); - $this->generatePercentage(true); + // + $row = self::incrementRead($this->id); PushTask::push([ - 'userid' => $this->userid, + 'userid' => $row->userid, 'msg' => [ 'type' => 'dialog', 'mode' => 'readed', 'data' => [ - 'id' => $this->id, - 'read' => $this->read, - 'percentage' => $this->percentage, + 'id' => $row->id, + 'read' => $row->read, + 'percentage' => $row->percentage, ], ] ]); @@ -252,6 +241,24 @@ class WebSocketDialogMsg extends AbstractModel return true; } + /** + * 增加已读数量 + * @param $msgId + * @return self + */ + private static function incrementRead($msgId) + { + return self::transaction(function () use ($msgId) { + $model = WebSocketDialogMsg::lockForUpdate()->find($msgId); + if (!$model) { + throw new \Exception('记录不存在'); + } + + $model->increment('read'); + return WebSocketDialogMsg::find($msgId); + }); + } + /** * emoji回复 * @param $symbol