]> BookStack Code Mirror - bookstack/blob - app/Entities/BookChild.php
Updated styles to use logical properties/values
[bookstack] / app / Entities / BookChild.php
1 <?php namespace BookStack\Entities;
2
3 use Illuminate\Database\Eloquent\Builder;
4 use Illuminate\Database\Eloquent\Relations\BelongsTo;
5
6 /**
7  * Class BookChild
8  * @property int $book_id
9  * @property int $priority
10  * @property Book $book
11  * @method Builder whereSlugs(string $bookSlug, string $childSlug)
12  */
13 class BookChild extends Entity
14 {
15
16     /**
17      * Scope a query to find items where the the child has the given childSlug
18      * where its parent has the bookSlug.
19      */
20     public function scopeWhereSlugs(Builder $query, string $bookSlug, string $childSlug)
21     {
22         return $query->with('book')
23             ->whereHas('book', function (Builder $query) use ($bookSlug) {
24                 $query->where('slug', '=', $bookSlug);
25             })
26             ->where('slug', '=', $childSlug);
27     }
28
29     /**
30      * Get the book this page sits in.
31      * @return BelongsTo
32      */
33     public function book(): BelongsTo
34     {
35         return $this->belongsTo(Book::class);
36     }
37
38     /**
39      * Change the book that this entity belongs to.
40      */
41     public function changeBook(int $newBookId): Entity
42     {
43         $this->book_id = $newBookId;
44         $this->refreshSlug();
45         $this->save();
46         $this->refresh();
47
48         // Update related activity
49         $this->activity()->update(['book_id' => $newBookId]);
50
51         // Update all child pages if a chapter
52         if ($this instanceof Chapter) {
53             foreach ($this->pages as $page) {
54                 $page->changeBook($newBookId);
55             }
56         }
57
58         return $this;
59     }
60 }