From a5741dd1c83b4808d9ff4b1a430e178488a18a43 Mon Sep 17 00:00:00 2001 From: Jeff Date: Fri, 23 Feb 2018 15:43:56 -0300 Subject: [PATCH] Using relationships instead of JOINs to reduce the excecution time --- src/Post.php | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/Post.php b/src/Post.php index 2cc6721..5da14e4 100644 --- a/src/Post.php +++ b/src/Post.php @@ -188,39 +188,54 @@ public function scopeId($query, $id) * Get posts with a given category * * @param object $query The query object - * @param string $slug The slug name of the category + * @param string|array $slug List of categories * * @return object The query object */ public function scopeCategory($query, $slug) { - return $this->taxonomy($query, 'category', $slug); + return $query->whereHas('categories', function ($q) use ($slug) { + if (is_array($slug)) { + $q->whereIn('terms.slug', $slug); + } + $q->where('terms.slug', $slug); + })->distinct('posts.ID'); } /** * Get posts with a given tag * * @param object $query The query object - * @param string $slug The slug name of the tag + * @param string|array $slug List of tags * * @return object The query object */ public function scopeTag($query, $slug) { - return $this->taxonomy($query, 'post_tag', $slug); + return $query->whereHas('tags', function ($q) use ($slug) { + if (is_array($slug)) { + $q->whereIn('terms.slug', $slug); + } + $q->where('terms.slug', $slug); + })->distinct('posts.ID'); } /** * Get posts with a given format * * @param object $query The query object - * @param string $slug The slug name of the format + * @param string|array $slug List of formats * * @return object The query object */ public function scopeFormat($query, $slug) { - return $this->taxonomy($query, 'post_format', $slug); + return $query->whereHas('formats', function ($q) use ($slug) { + if (is_array($slug)) { + $q->whereIn('terms.slug', $slug); + } + $q->where('terms.slug', $slug); + })->distinct('posts.ID'); } /**