public function sort($id, $sort) { if (!in_array($sort, array('up', 'down'))) { return redirect_message(array('admin', $this->get_class()), array('_flash_message' => '排序失敗!')); } $total = Promo::count(); switch ($sort) { case 'up': $sort = $this->promo->sort; $this->promo->sort = $this->promo->sort + 1 >= $total ? 0 : $this->promo->sort + 1; break; case 'down': $sort = $this->promo->sort; $this->promo->sort = $this->promo->sort - 1 < 0 ? $total - 1 : $this->promo->sort - 1; break; } Promo::addConditions($conditions, 'sort = ?', $this->promo->sort); $promo = $this->promo; $update = Promo::transaction(function () use($conditions, $promo, $sort) { if (($next = Promo::find('one', array('conditions' => $conditions))) && (($next->sort = $sort) || true)) { if (!$next->save()) { return false; } } if (!$promo->save()) { return false; } return true; }); if (!$update) { return redirect_message(array('admin', $this->get_class()), array('_flash_message' => '排序失敗!', 'posts' => $posts)); } return redirect_message(array('admin', $this->get_class()), array('_flash_message' => '排序成功!')); }