Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using relationships instead of JOINs to reduce the excecution time #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions src/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

/**
Expand Down