-
Notifications
You must be signed in to change notification settings - Fork 0
/
OrderableCollection.php
54 lines (45 loc) · 1.73 KB
/
OrderableCollection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace Baril\Orderly;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
class OrderableCollection extends EloquentCollection
{
public function saveOrder()
{
if ($this->isEmpty()) {
return $this;
}
$instance = $this->first();
$orderColumn = $instance->getOrderColumn();
$groupColumn = $instance->getGroupColumn();
// Check that all items are in the same group:
if ($groupColumn) {
foreach ((array) $groupColumn as $column) {
if ($this->pluck($column)->unique()->count() > 1) {
throw new GroupException('All models must be in same group!');
}
}
}
// Get current positions:
$positions = $this->pluck($orderColumn)->sort()->all();
reset($positions);
// Save the new order:
$instance->getConnection()->transaction(function () use ($orderColumn, &$positions) {
$this->values()->each(function ($model) use ($orderColumn, &$positions) {
// Update the order field without triggering the listeners:
$model->newQuery()->whereKey($model->getKey())->update([$orderColumn => current($positions)]);
$model->setAttribute($orderColumn, current($positions));
next($positions);
});
});
return $this;
}
public function setOrder($ids)
{
$count = $this->count();
$ordered = $this->sortBy(function ($item) use ($ids, $count) {
$index = array_search($item->getKey(), $ids);
return ($index === false) ? $count + $item->getPosition() : $index;
});
return $ordered->saveOrder();
}
}