3 namespace BookStack\Entities\Models;
5 use BookStack\References\ReferenceUpdater;
6 use Illuminate\Database\Eloquent\Builder;
7 use Illuminate\Database\Eloquent\Relations\BelongsTo;
12 * @property int $book_id
13 * @property int $priority
14 * @property string $book_slug
15 * @property Book $book
17 * @method Builder whereSlugs(string $bookSlug, string $childSlug)
19 abstract class BookChild extends Entity
21 protected static function boot()
25 // Load book slugs onto these models by default during query-time
26 static::addGlobalScope('book_slug', function (Builder $builder) {
27 $builder->addSelect(['book_slug' => function ($builder) {
28 $builder->select('slug')
30 ->whereColumn('books.id', '=', 'book_id');
36 * Scope a query to find items where the child has the given childSlug
37 * where its parent has the bookSlug.
39 public function scopeWhereSlugs(Builder $query, string $bookSlug, string $childSlug)
41 return $query->with('book')
42 ->whereHas('book', function (Builder $query) use ($bookSlug) {
43 $query->where('slug', '=', $bookSlug);
45 ->where('slug', '=', $childSlug);
49 * Get the book this page sits in.
51 public function book(): BelongsTo
53 return $this->belongsTo(Book::class)->withTrashed();
57 * Change the book that this entity belongs to.
59 public function changeBook(int $newBookId): Entity
61 $oldUrl = $this->getUrl();
62 $this->book_id = $newBookId;
67 if ($oldUrl !== $this->getUrl()) {
68 app()->make(ReferenceUpdater::class)->updateEntityReferences($this, $oldUrl);
71 // Update all child pages if a chapter
72 if ($this instanceof Chapter) {
73 foreach ($this->pages()->withTrashed()->get() as $page) {
74 $page->changeBook($newBookId);