Skip to content

Commit

Permalink
Update SortableTrait.php
Browse files Browse the repository at this point in the history
  • Loading branch information
EmanueleCoppola authored Nov 21, 2018
1 parent 18ca2ba commit 811a374
Showing 1 changed file with 11 additions and 23 deletions.
34 changes: 11 additions & 23 deletions src/SortableTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,41 +255,29 @@ public function moveToEnd()
}

/**
* Move a model into a specified position
* Positions starts at 1. 0 would be the same as start.
* Moves this model to a specified position
*
* @param int $newPosition
* @param integer $position
*
* @return $this
*/
public function moveToPosition(int $newPosition): self
public function moveToPosition($position)
{
$orderColumnName = $this->determineOrderColumnName();

$newPosition = max($newPosition, 0);
$position = max(1, min($position, $this->getHighestOrderNumber()));

$currentPosition = (int) $this->$orderColumnName;
$orderAtPosition = $this->getOrderNumberAtPosition($newPosition);

// No need to do anything, it is already in the correct position
if ($currentPosition === $newPosition) {
return $this;
}
$orderColumnName = $this->determineOrderColumnName();

if ($newPosition > $currentPosition) {
// The model is moving up
$this->buildSortQuery()->where([[$this->getKeyName(), '!=', $this->id], [$orderColumnName, '>', $currentPosition], [$orderColumnName, '<=', $orderAtPosition]])->decrement($orderColumnName);
} else {
// The model is moving down
$this->buildSortQuery()->where([[$this->getKeyName(), '!=', $this->id], [$orderColumnName, '<', $currentPosition], [$orderColumnName, '>=', $orderAtPosition]])->increment($orderColumnName);
}
$this->buildSortQuery()
->where($this->getKeyName(), '!=', $this->id)
->where($orderColumnName, '>=', $position)
->increment($orderColumnName);

$this->$orderColumnName = $orderAtPosition;
$this->$orderColumnName = $position;
$this->save();

return $this;
}

/**
* Build eloquent builder of sortable.
*
Expand Down

0 comments on commit 811a374

Please sign in to comment.