'Select Data from Previous and Next Results In One Query : Convert From Sql Query To Eloquent Laravel
I'm building and prev and next link in a page, I wish to achieve this in one query. I have the working Raw Sql, I can't seem to be able to convert to Eloquent Laravel. I want to have the multiple model options like so: prev() , next(), prevAndNext() and prevAndNextId() .
from this:
public function next(){
return self::select('gift_card_id' , 'gift_card_slug')->where('gift_card_id', '>', $this->gift_card_id)->orderBy('gift_card_id','asc')->first();
}
public function previous(){
return self::select('gift_card_id' , 'gift_card_slug')->where('gift_card_id', '<', $this->gift_card_id)->orderBy('gift_card_id','desc')->first();
}
to this : prevAndNext()
select
gift_card_id , gift_card_slug
from gift_cards
where (
`gift_card_id` = IFNULL((select min(`gift_card_id`) from gift_cards where `gift_card_id` > 1343),null)
or
`gift_card_id` = IFNULL((select max(`gift_card_id`) from gift_cards where `gift_card_id` < 1343),null)
)
Other aproch just to get the ID : prevAndNextId()
SELECT
IFNULL(
(SELECT gift_card_id FROM gift_cards WHERE gift_card_id < 1345 ORDER BY gift_card_id DESC LIMIT 1),null) as previous,
IFNULL(
(SELECT gift_card_id FROM gift_cards WHERE gift_card_id > 1345 ORDER BY gift_card_id ASC LIMIT 1),null) as next
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
