-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate.php
More file actions
executable file
·103 lines (93 loc) · 2.95 KB
/
Copy pathUpdate.php
File metadata and controls
executable file
·103 lines (93 loc) · 2.95 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace Pet\DataBase;
use Pet\DataBase\Delete;
use Pet\Model\Model;
use Pet\Tools\Tools;
trait Update
{
/**
* update
*
* @param array $arrayKeyAndValue
* @return Model
*/
public function update(array $arrayKeyAndValue): Model
{
$this->arrayQuote($arrayKeyAndValue);
$str = Tools::array_implode(',', $arrayKeyAndValue, "`[key]`=[val]");
$table = $this->getTableName();
$this->strQuery = "UPDATE `$table` SET $str";
$this->SUB = "UPDATE";
return $this;
}
/**
* updateBatch — массовое обновление с CASE.
*
* @param array $rows Массив строк с ключами
* @param string $keyField Поле-идентификатор (по умолчанию id)
* @return bool
*/
public function updateBatch(array $rows, string $keyField = 'id'): bool
{
if (empty($rows)) {
return false;
}
$table = $this->getTableName();
$keys = array_keys(reset($rows));
$ids = [];
$cases = [];
foreach ($keys as $field) {
if ($field === $keyField) continue;
$caseSql = "`$field` = CASE ";
foreach ($rows as $row) {
$id = $row[$keyField];
$val = $row[$field];
$ids[] = $id;
$idSql = is_string($id) ? "'$id'" : $id;
if ($val === null) {
$valSql = 'NULL';
} elseif (is_string($val)) {
$valSql = "'$val'";
} else {
$valSql = $val;
}
$caseSql .= "WHEN `$keyField` = $idSql THEN $valSql ";
}
$caseSql .= "END";
$cases[] = $caseSql;
}
$ids = array_unique($ids);
$idList = implode(',', array_map(fn($id) => is_string($id) ? "'$id'" : $id, $ids));
$this->strQuery = "UPDATE `$table` SET " . implode(', ', $cases) . " WHERE `$keyField` IN ($idList)";
$this->SUB = "UPDATE_BATCH";
return $this->execute();
}
/**
* increment — увеличить поле на значение.
*
* @param string $field
* @param int|float $amount
* @return Model
*/
public function increment(string $field, int|float $amount = 1): Model
{
$table = $this->getTableName();
$this->strQuery = "UPDATE `$table` SET `$field` = `$field` + $amount";
$this->SUB = "UPDATE";
return $this;
}
/**
* decrement — уменьшить поле на значение.
*
* @param string $field
* @param int|float $amount
* @return Model
*/
public function decrement(string $field, int|float $amount = 1): Model
{
$table = $this->getTableName();
$this->strQuery = "UPDATE `$table` SET `$field` = `$field` - $amount";
$this->SUB = "UPDATE";
return $this;
}
}