best way for next/previous buttons for entries in yii

孤者浪人 提交于 2020-01-02 06:59:12

问题


I would like to know what is the best way to create next/previous buttons for an entry in the database. Let's say we have a table with images and every image has an ID and a Path. If the current image has ID equal to "9" how can I get the next and the previous IDs?

I already found a solution for this right here https://stackoverflow.com/a/8874382 but this seems to be the latest choice. If we have over 10000 entries (images) in our database, this will overwhelm the server. First of all, it selects all entries and then it tries to copy all of the results in an array. After this, the array is searched for the current ID. It's very slow.

I was thinking about a limit set to the query but how can I get the next and previous pictures after this?

Another (better, I think) solution would be to get the ID of the current picture and decrement/increment it until another image with the new ID is found. I think this is faster than the function provided in the link.

Also, in the same link there is another idea, to set the prev_id and next_id in the model of the current picture. But here we have the same problem, how do we find them? And even if we find them, is it correct to store data about prev/next pictures in the current picture? It does not seem to be right but I'm sure it's more convenient when you need to access that data.

Thank you!


回答1:


This query will only returns the next/previous row, if found. Better? (Should be implemented in your model class).

public function getNextId()
{
    $record=self::model()->find(array(
            'condition' => 'id>:current_id',
            'order' => 'id ASC',
            'limit' => 1,
            'params'=>array(':current_id'=>$this->id),
    ));
    if($record!==null)
        return $record->id;
    return null;
}
public function getPreviousId()
{
    $record=self::model()->find(array(
            'condition' => 'id<:current_id',
            'order' => 'id DESC',
            'limit' => 1,
            'params'=>array(':current_id'=>$this->id),
    ));
    if($record!==null)
        return $record->id;
    return null;
}


来源:https://stackoverflow.com/questions/13185939/best-way-for-next-previous-buttons-for-entries-in-yii

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!