1<?php
2
3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
4// See the LICENCE file in the repository root for full licence text.
5
6namespace App\Models;
7
8/**
9 * @property Comment $comment
10 * @property int $comment_id
11 * @property \Carbon\Carbon|null $created_at
12 * @property int $id
13 * @property \Carbon\Carbon|null $updated_at
14 * @property User $user
15 * @property int $user_id
16 */
17class CommentVote extends Model
18{
19 public function comment()
20 {
21 return $this->belongsTo(Comment::class);
22 }
23
24 public function user()
25 {
26 return $this->belongsTo(User::class, 'user_id');
27 }
28
29 public function delete()
30 {
31 return $this->getConnection()->transaction(function () {
32 $decrementParentCounter = $this->exists;
33 $result = parent::delete();
34
35 if ($result && $decrementParentCounter) {
36 $this->comment()->getQuery()->withoutTrashed()->update([
37 'votes_count_cache' => db_unsigned_increment('votes_count_cache', -1),
38 ]);
39 }
40
41 return $result;
42 });
43 }
44
45 public function save(array $options = [])
46 {
47 if (optional($this->comment)->trashed()) {
48 return false;
49 }
50
51 return $this->getConnection()->transaction(function () use ($options) {
52 $incrementParentCounter = !$this->exists;
53 $result = parent::save($options);
54
55 if ($result && $incrementParentCounter) {
56 $this->comment()->getQuery()->withoutTrashed()->increment('votes_count_cache');
57 }
58
59 return $result;
60 });
61 }
62}