Passed
Push — master ( c57047...e9f946 )
by Mihail
06:06
created

CommentPost::getAnswer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace Apps\ActiveRecord;
4
5
use Ffcms\Core\App as MainApp;
6
use Ffcms\Core\Arch\ActiveModel;
7
use Ffcms\Core\Traits\SearchableTrait;
8
9
/**
10
 * Class CommentPost. Active record model for comment posts.
11
 * @package Apps\ActiveRecord
12
 * @property int $id
13
 * @property string $app_name
14
 * @property int $app_relation_id
15
 * @property int $user_id
16
 * @property string|null $guest_name
17
 * @property string $message
18
 * @property string $lang
19
 * @property boolean $moderate
20
 * @property string $created_at
21
 * @property string $updated_at
22
 * @property User $user
23
 * @property CommentAnswer[] $answers
24
 */
25
class CommentPost extends ActiveModel
26
{
27
    use SearchableTrait;
28
29
    protected $casts = [
30
        'id' => 'integer',
31
        'app_name' => 'string',
32
        'app_relation_id' => 'integer',
33
        'user_id' => 'integer',
34
        'guest_name' => 'string',
35
        'message' => 'string',
36
        'lang' => 'string',
37
        'moderate' => 'boolean'
38
    ];
39
40
    protected $searchable = [
41
        'columns' => [
42
            'message' => 1
43
        ]
44
    ];
45
46
    /**
47
     * Get user relation object
48
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
49
     */
50
    public function user()
51
    {
52
        return $this->belongsTo(User::class, 'user_id');
53
    }
54
55
    /**
56
     * Get answers relation objects
57
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
58
     */
59
    public function answers()
60
    {
61
        return $this->hasMany(CommentAnswer::class, 'comment_id');
62
    }
63
64
    /**
65
     * Get answers count for post comment id
66
     * @return int
67
     */
68
    public function getAnswerCount()
69
    {
70
        // check if count is cached
71
        if (MainApp::$Memory->get('commentpost.answer.count.' . $this->id) !== null) {
72
            return MainApp::$Memory->get('commentpost.answer.count.' . $this->id);
73
        }
74
        // get count from db
75
        $count = CommentAnswer::where('comment_id', $this->id)
76
            ->where('moderate', 0)
77
            ->count();
78
        // save in cache
79
        MainApp::$Memory->set('commentpost.answer.count.' . $this->id, $count);
80
        return $count;
81
    }
82
}
83