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
My Answer:
>where('id', '>', $this->id)->orderBy('id', 'asc')->first();_ }_ public function prev(){_ return self::select('gift_card_id' , 'gift_card_slug')->where('id', '<', $this->id)->orderBy('id', 'desc')->first();_ }_ public function prevAndNext(){_ $prev = $this->prev();_ $next = $this->next();_ return ['prev' => $prev, 'next' => $next];_ }_ public function prevAndNextId(){_ $prev = $this->prev();_ $next = $this->next();_ return ['prev_id' => $prev->id, 'next_id' => $next->id];_ }_}__to this:_
php_ public function next(){_ return self::where('id', '>', $this->id)->orderBy('id', 'asc')->first();_ }_ public function prev(){_ return self::where('id', '<', $this->id)->orderBy('id', 'desc')->first();_ }_ public function prevAndNext(){_ $prev = $this->prev();_ $next = $this->next();_ return ['prev' => $prev, 'next' => $next];_ }_ public function prevAndNextId(){_ $prev = $this->prev();_ $next = $this->next();_ return ['prev_id' => $prev->id, 'next_id' => $next->id];_ }_
Rate this post
5 of 5 based on 9734 votesComments