]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
Queries: Update API to align data with previous versions
[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\Builder;
7 use Illuminate\Database\Eloquent\Relations\BelongsTo;
8
9 /**
10  * Class BookChild.
11  *
12  * @property int    $book_id
13  * @property int    $priority
14  * @property string $book_slug
15  * @property Book   $book
16  */
17 abstract class BookChild extends Entity
18 {
19     /**
20      * Get the book this page sits in.
21      */
22     public function book(): BelongsTo
23     {
24         return $this->belongsTo(Book::class)->withTrashed();
25     }
26
27     /**
28      * Change the book that this entity belongs to.
29      */
30     public function changeBook(int $newBookId): Entity
31     {
32         $oldUrl = $this->getUrl();
33         $this->book_id = $newBookId;
34         $this->refreshSlug();
35         $this->save();
36         $this->refresh();
37
38         if ($oldUrl !== $this->getUrl()) {
39             app()->make(ReferenceUpdater::class)->updateEntityReferences($this, $oldUrl);
40         }
41
42         // Update all child pages if a chapter
43         if ($this instanceof Chapter) {
44             foreach ($this->pages()->withTrashed()->get() as $page) {
45                 $page->changeBook($newBookId);
46             }
47         }
48
49         return $this;
50     }
51 }