Reputation: 13
Quick question to Laravel and mysql expert, I have three queries as follow:-
// Only Can use slug here
$post = Post::whereSlug($slug)->with(['category', 'author'])->first();
$prevPost = Post::where('id', '<', $post->id)
->select('id', 'title', 'slug')
->orderBy('id', 'desc')
->first()
$nextPost = Post::where('id', '>', $postId)
->select('id', 'title', 'slug')
->orderBy('id')
->first()
Is there any way i can join all three queries into one. i want to join all three queries into one, For last two queries i need to have $post->id. i want to have one result of containing desired post, previous post to desired post and next post to desired post
Upvotes: 0
Views: 199
Reputation: 1167
There is no actual Eloquent way to combine all of these queries into a single one. You could use Fluent raw queries along with some tricky window functions, however those would be time consuming to write and would be dependent on your specific type of SQL.
Upvotes: 1
Reputation: 3543
Best approach would be to use some kind of scope to achieve that:
public function scopeOfId($query, $id, $operator, $orderBy = "asc") {
$query->where('id', $operator, $id)
->select('id', 'title', 'slug')
->orderBy('id', $orderBy)
}
Then you would call it Post::ofId(5, "<")
or Post::ofId(5, "<", "desc")
or any combination really. Also where('id', '>', $postId)
and where('id', '<', $postId)
can be combined into this single where statemenet => where('id', '!=', $postId)
.
Upvotes: 0