]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
DB: Started update of entity loading to avoid global selects
[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  * @method Builder whereSlugs(string $bookSlug, string $childSlug)
18  */
19 abstract class BookChild extends Entity
20 {
21     /**
22      * Scope a query to find items where the child has the given childSlug
23      * where its parent has the bookSlug.
24      */
25     public function scopeWhereSlugs(Builder $query, string $bookSlug, string $childSlug)
26     {
27         return $query->with('book')
28             ->whereHas('book', function (Builder $query) use ($bookSlug) {
29                 $query->where('slug', '=', $bookSlug);
30             })
31             ->where('slug', '=', $childSlug);
32     }
33
34     /**
35      * Get the book this page sits in.
36      */
37     public function book(): BelongsTo
38     {
39         return $this->belongsTo(Book::class)->withTrashed();
40     }
41
42     /**
43      * Change the book that this entity belongs to.
44      */
45     public function changeBook(int $newBookId): Entity
46     {
47         $oldUrl = $this->getUrl();
48         $this->book_id = $newBookId;
49         $this->refreshSlug();
50         $this->save();
51         $this->refresh();
52
53         if ($oldUrl !== $this->getUrl()) {
54             app()->make(ReferenceUpdater::class)->updateEntityReferences($this, $oldUrl);
55         }
56
57         // Update all child pages if a chapter
58         if ($this instanceof Chapter) {
59             foreach ($this->pages()->withTrashed()->get() as $page) {
60                 $page->changeBook($newBookId);
61             }
62         }
63
64         return $this;
65     }
66 }