|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace app\traits; |
|
4
|
|
|
|
|
5
|
|
|
use yii; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Trait for sorting models, that use app\behaviors\Sortable |
|
9
|
|
|
*/ |
|
10
|
|
|
trait SortModels |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* Sort records by their id list. |
|
14
|
|
|
* Note: you must manually call refresh() on needed models |
|
15
|
|
|
* @param array $ids array of records id in needed order(ie. [4, 3, 1, 2]) |
|
16
|
|
|
* @param string $field Field that stores sort order |
|
17
|
|
|
* @return bool |
|
18
|
|
|
* @throws yii\db\Exception |
|
19
|
|
|
*/ |
|
20
|
|
View Code Duplication |
public static function sortModels($ids, $field = 'sort_order') |
|
21
|
|
|
{ |
|
22
|
|
|
$priorities = []; |
|
23
|
|
|
$start=0; |
|
24
|
|
|
$ids_sorted = $ids; |
|
25
|
|
|
sort($ids_sorted); |
|
26
|
|
|
foreach ($ids as $id) { |
|
27
|
|
|
$priorities[$id] = $ids_sorted[$start++]; |
|
28
|
|
|
} |
|
29
|
|
|
$sql = "UPDATE " |
|
30
|
|
|
. static::tableName() |
|
31
|
|
|
. " SET $field = " |
|
32
|
|
|
. static::generateCase($priorities) |
|
33
|
|
|
. " WHERE id IN(" . implode(', ', $ids) |
|
34
|
|
|
. ")"; |
|
35
|
|
|
return Yii::$app->db->createCommand( |
|
36
|
|
|
$sql |
|
37
|
|
|
)->execute() > 0; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
View Code Duplication |
public static function generateCase($priorities) |
|
41
|
|
|
{ |
|
42
|
|
|
$result = 'CASE `id`'; |
|
43
|
|
|
foreach ($priorities as $k => $v) { |
|
44
|
|
|
$result .= ' when "' . $k . '" then "' . $v . '"'; |
|
45
|
|
|
} |
|
46
|
|
|
return $result . ' END'; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public static function moveIdBefore($id, $id_before, $field = 'sort_order') |
|
|
|
|
|
|
50
|
|
|
{ |
|
51
|
|
|
//! @todo Переписать, чтобы не использовать ActiveRecord, а обходиться обычными запросами в базу(за один запрос можно получить sort_order для двух ID) |
|
|
|
|
|
|
52
|
|
|
$current_model = static::findOne($id); |
|
53
|
|
|
$another_model = static::findOne($id_before); |
|
54
|
|
|
return $current_model->moveBefore($another_model, $field); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public static function moveIdAfter($id, $id_after, $field = 'sort_order') |
|
|
|
|
|
|
58
|
|
|
{ |
|
59
|
|
|
//! @todo Переписать, чтобы не использовать ActiveRecord, а обходиться обычными запросами в базу(за один запрос можно получить sort_order для двух ID) |
|
|
|
|
|
|
60
|
|
|
$current_model = static::findOne($id); |
|
61
|
|
|
$another_model = static::findOne($id_after); |
|
62
|
|
|
return $current_model->moveAfter($another_model, $field); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@returnannotation as described here.