]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
c73fa3959423598da0e1619c07d9720760374a39
[bookstack] / app / Entities / Models / BookChild.php
1 <?php namespace BookStack\Entities\Models;
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 abstract 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      */
32     public function book(): BelongsTo
33     {
34         return $this->belongsTo(Book::class)->withTrashed();
35     }
36
37     /**
38      * Change the book that this entity belongs to.
39      */
40     public function changeBook(int $newBookId): Entity
41     {
42         $this->book_id = $newBookId;
43         $this->refreshSlug();
44         $this->save();
45         $this->refresh();
46
47         // Update all child pages if a chapter
48         if ($this instanceof Chapter) {
49             foreach ($this->pages()->withTrashed()->get() as $page) {
50                 $page->changeBook($newBookId);
51             }
52         }
53
54         return $this;
55     }
56 }