Answer the question
In order to leave comments, you need to log in
The brain is already boiling, what's wrong here?
Hi all. I have a problem with the code, it works, but it's very strange...
O_o // Upd. In the code example - using Phalcon
Suppose there is a table with such fields. Further, I will call it Sections
And now the task Suppose I need to put a category with
ID
4 in place of category 3. Accordingly, category 3 will take the place of category 4. Everything seems to be simple ...
I decided to make the move as follows:
then 2 identical IDs cannot be. I so shall tell create temporary ID which is not present in the table yet. (The number of rows in the table + 1)
Next, for the category with ID 3, I change the ID to one that is not yet in the table.
Since the category with ID 4 has been vacated, I move category 3 to the place (replace ID).
Well, now the place has been freed up again from under category 4, so I move category 3 from the "time line" there.
It seems to be logical ...
In the form of code, it all looks like this:
public function upAction ($id = 0)
{
$allSections = new Sections();
$currentSection = $allSections->findFirstById($id);
if (!$currentSection)
{
$this->flash->warning('Категория не найдена');
return $this->response->redirect('dashboard-section');
}
/* <Костыль> */
$numRows = $allSections->find()->count();// Общее количество категорий
$notDefineId = ++$numRows;// ID которого ещё нет в таблице. Туда временно перенесём категорию Б
$nearbySection = $allSections->findFirst([
'conditions' => 'id != :current_section: AND id > :current_section:',
'bind' => [
'current_section' => $currentSection->id
]
]);// Ищем строку ближайшую к текущей.
if (!$nearbySection)
{
$this->flash->warning('Категория и так занимает первую позицию');
return $this->response->redirect('dashboard-section');
}
$currentId = $currentSection->id;// ID категории А
$nearbyId = $nearbySection->id;// ID категории Б
$nearbySection->id = $notDefineId;// Перемещаем категорию Б во временную строку
$nearbySection->save();// Сохраняем
$currentSection->id = $nearbyId;// ID категории А заменяем на ID категории Б
$currentSection->save();// сохраняем
$nearbySection->id = $currentId;// перенсим категорию Б из временной строки на место категории А
$nearbySection->save();// сохраняем
$this->flash->success('Категория успешно перемещена');
/* </костыль> */
return $this->response->redirect('dashboard-section');
}
Answer the question
In order to leave comments, you need to log in
It may be easier to use stupid sorting. additional field ord and store the sort index in it. as a more convenient solution for directories, I advise you to use nested sets
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question