diff --git a/src/Core/Models/Discussion.php b/src/Core/Models/Discussion.php index a6a7aaa34..4211e755c 100755 --- a/src/Core/Models/Discussion.php +++ b/src/Core/Models/Discussion.php @@ -68,7 +68,7 @@ class Discussion extends Model static::deleted(function ($discussion) { $discussion->raise(new DiscussionWasDeleted($discussion)); - $discussion->posts()->delete(); + $discussion->posts()->allTypes()->delete(); $discussion->readers()->detach(); }); } diff --git a/src/Core/Models/Post.php b/src/Core/Models/Post.php index c387331aa..1a48bc71b 100755 --- a/src/Core/Models/Post.php +++ b/src/Core/Models/Post.php @@ -65,6 +65,8 @@ class Post extends Model static::deleted(function ($post) { $post->raise(new PostWasDeleted($post)); }); + + static::addGlobalScope(new RegisteredTypesScope); } /** @@ -119,6 +121,18 @@ class Post extends Model return array_map('intval', $query->get(['id'])->fetch('id')->all()); } + /** + * Get all posts, regardless of their type, by removing the + * `RegisteredTypesScope` global scope constraints applied on this model. + * + * @param \Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Eloquent\Builder + */ + public function scopeAllTypes($query) + { + return $this->removeGlobalScopes($query); + } + /** * Create a new model instance according to the post's type. * @@ -155,4 +169,9 @@ class Post extends Model { static::$types[$type] = $class; } + + public static function getTypes() + { + return static::$types; + } } diff --git a/src/Core/Models/RegisteredTypesScope.php b/src/Core/Models/RegisteredTypesScope.php new file mode 100644 index 000000000..007e08960 --- /dev/null +++ b/src/Core/Models/RegisteredTypesScope.php @@ -0,0 +1,55 @@ +whereIn('type', array_keys($model::getTypes())); + } + + /** + * Remove the scope from the given Eloquent query builder. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @param \Illuminate\Database\Eloquent\Model $model + * @return void + */ + public function remove(Builder $builder, Model $model) + { + $query = $builder->getQuery(); + + foreach ((array) $query->wheres as $key => $where) + { + if ($this->isTypeConstraint($where)) + { + unset($query->wheres[$key]); + + $query->wheres = array_values($query->wheres); + } + } + } + + /** + * Determine if the given where clause is a type constraint. + * + * @param array $where + * @param string $column + * @return bool + */ + protected function isTypeConstraint(array $where) + { + return $where['type'] == 'In' && $where['column'] == 'type'; + } + +}