]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
API: Added comment-read endpoint, added api docs section descriptions
[bookstack] / app / Entities / Models / BookChild.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use BookStack\References\ReferenceUpdater;
6 use Illuminate\Database\Eloquent\Relations\BelongsTo;
7
8 /**
9  * Class BookChild.
10  *
11  * @property int    $book_id
12  * @property int    $priority
13  * @property string $book_slug
14  * @property Book   $book
15  */
16 abstract class BookChild extends Entity
17 {
18     /**
19      * Get the book this page sits in.
20      */
21     public function book(): BelongsTo
22     {
23         return $this->belongsTo(Book::class)->withTrashed();
24     }
25
26     /**
27      * Change the book that this entity belongs to.
28      */
29     public function changeBook(int $newBookId): self
30     {
31         $oldUrl = $this->getUrl();
32         $this->book_id = $newBookId;
33         $this->unsetRelation('book');
34         $this->refreshSlug();
35         $this->save();
36
37         if ($oldUrl !== $this->getUrl()) {
38             app()->make(ReferenceUpdater::class)->updateEntityReferences($this, $oldUrl);
39         }
40
41         // Update all child pages if a chapter
42         if ($this instanceof Chapter) {
43             foreach ($this->pages()->withTrashed()->get() as $page) {
44                 $page->changeBook($newBookId);
45             }
46         }
47
48         return $this;
49     }
50 }