How to retrieve the next item in a list of MySQL records?

耗尽温柔 提交于 2019-12-31 05:19:35

问题


I'm working with symfony using Propel trying to create functionality for back and next buttons:

$c = new Criteria();

$c->add(CartPeer::CATEGORY, $category);
$c->add(CartPeer::ITEM_ID, $item->getItemId(), Criteria::GREATER_THAN);
$c->addAscendingOrderByColumn(CartPeer::ITEM_NAME);

$this->next = CartPeer::doSelectOne($c);

Now, this works fine if the item's identifiers are in ascending order, but usually this is not the case.

How can I modify this code so it selects the item immediately after the current $item in the list of records returned instead of selecting one with the next ascending numerical ID?

Example:

Record: 0 | ItemID: 5
Record: 1 | ItemID: 2
Record: 2 | ItemID: 7 <-- $item
Record: 3 | ItemID: 4 <-- I want this to be $next
Record: 4 | ItemID: 9

回答1:


I don't actually use Symfony, but if you're using an even remotely recent version of Propel with it then you have access to the paginate() method which may be a lot better in the end for you.

$pager = CartQuery::create()
           ->filterByCategory($category)
           ->orderBy(CartPeer::ITEM_NAME)
           ->paginate($pageToLoad, $resultsPerPage);
foreach($pager as $result) {
  // do something with the record
}
if ($pager->haveToPaginate()) {
  // build some paging items using PropelModelPager methods:
  if (!$pager->isFirstPage()) {
    echo "<a href='?page=".$pager->getPreviousPage()."'>Previous</a>";
  }
  if (!$pager->isLastPage()) {
    echo "<a href='?page=".$pager->getNextPage()."'>Next</a>";
  }
}

If you really want to do it your way, you may want to eliminate the restriction by ItemId entirely and simply add an offset along with your limit:

// This will be however many results have already been shown (page size?)
$offset = 10;

$c = new Criteria();
$c->add(CartPeer::CATEGORY, $category);
$c->addAscendingOrderByColumn(CartPeer::ITEM_NAME);
$c->setOffset($offset);
$this->next = CartPeer::doSelectOne($c);


来源:https://stackoverflow.com/questions/15147694/how-to-retrieve-the-next-item-in-a-list-of-mysql-records

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