]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/BookChild.php
Improved shelf book management interface
[bookstack] / app / Entities / Models / BookChild.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use Illuminate\Database\Eloquent\Builder;
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  * @method Builder whereSlugs(string $bookSlug, string $childSlug)
17  */
18 abstract class BookChild extends Entity
19 {
20     protected static function boot()
21     {
22         parent::boot();
23
24         // Load book slugs onto these models by default during query-time
25         static::addGlobalScope('book_slug', function (Builder $builder) {
26             $builder->addSelect(['book_slug' => function ($builder) {
27                 $builder->select('slug')
28                     ->from('books')
29                     ->whereColumn('books.id', '=', 'book_id');
30             }]);
31         });
32     }
33
34     /**
35      * Scope a query to find items where the child has the given childSlug
36      * where its parent has the bookSlug.
37      */
38     public function scopeWhereSlugs(Builder $query, string $bookSlug, string $childSlug)
39     {
40         return $query->with('book')
41             ->whereHas('book', function (Builder $query) use ($bookSlug) {
42                 $query->where('slug', '=', $bookSlug);
43             })
44             ->where('slug', '=', $childSlug);
45     }
46
47     /**
48      * Get the book this page sits in.
49      */
50     public function book(): BelongsTo
51     {
52         return $this->belongsTo(Book::class)->withTrashed();
53     }
54
55     /**
56      * Change the book that this entity belongs to.
57      */
58     public function changeBook(int $newBookId): Entity
59     {
60         $this->book_id = $newBookId;
61         $this->refreshSlug();
62         $this->save();
63         $this->refresh();
64
65         // Update all child pages if a chapter
66         if ($this instanceof Chapter) {
67             foreach ($this->pages()->withTrashed()->get() as $page) {
68                 $page->changeBook($newBookId);
69             }
70         }
71
72         return $this;
73     }
74 }