]> BookStack Code Mirror - bookstack/blob - app/Comment.php
#47 Adds two attributes updated and created to display time to user.
[bookstack] / app / Comment.php
1 <?php
2
3 namespace BookStack;
4 use Illuminate\Support\Facades\DB;
5
6 class Comment extends Ownable
7 {
8     protected $fillable = ['text', 'html', 'parent_id'];
9     protected $appends = ['created', 'updated'];
10     /**
11      * Get the entity that this comment belongs to
12      * @return \Illuminate\Database\Eloquent\Relations\MorphTo
13      */
14     public function entity()
15     {
16         return $this->morphTo('entity');
17     }
18
19     /**
20      * Get the page that this comment is in.
21      * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
22      */
23     public function page()
24     {
25         return $this->belongsTo(Page::class);
26     }
27
28     /**
29      * Get the owner of this comment.
30      * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
31      */
32     public function user()
33     {
34         return $this->belongsTo(User::class);
35     }
36
37     public function getCommentsByPage($pageId, $commentId, $pageNum = 0, $limit = 0) {
38
39         $query = static::newQuery();
40         $query->join('users AS u', 'comments.created_by', '=', 'u.id');
41         $query->leftJoin('users AS u1', 'comments.updated_by', '=', 'u1.id');
42         $query->leftJoin('images AS i', 'i.id', '=', 'u.image_id');
43         $query->selectRaw('comments.id, text, html, comments.created_by, comments.updated_by, comments.created_at, comments.updated_at, '
44                 . 'u.name AS created_by_name, u1.name AS updated_by_name, '
45                 . '(SELECT count(c.id) FROM bookstack.comments c WHERE c.parent_id = comments.id AND page_id = ?) AS cnt_sub_comments, i.url AS avatar ',
46                 [$pageId]);
47
48         if (empty($commentId)) {
49             $query->whereRaw('page_id = ? AND parent_id IS NULL', [$pageId]);
50         } else {
51             $query->whereRaw('page_id = ? AND parent_id = ?', [$pageId, $commentId]);
52         }
53         $query->orderBy('created_at');
54         return $query;
55     }
56
57     public function getCreatedAttribute() {
58         $created = [
59             'day_time_str' => $this->created_at->toDayDateTimeString(),
60             'diff' => $this->created_at->diffForHumans()
61         ];
62         return $created;
63     }
64
65     public function getUpdatedAttribute() {
66         if (empty($this->updated_at)) {
67             return null;
68         }
69         $updated = [
70             'day_time_str' => $this->updated_at->toDayDateTimeString(),
71             'diff' => $this->updated_at->diffForHumans()
72         ];
73         return $updated;
74     }
75 }