Skip to content

Commit 0b6302a

Browse files
authored
add method updateWithTwoIndex
1 parent 64771c1 commit 0b6302a

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/Batch.php

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,70 @@ public function update(Model $table, array $values, string $index = null, bool $
107107
return $this->db->connection($this->getConnectionName($table))->update($query);
108108
}
109109

110+
/**
111+
* Update multiple rows
112+
* @param Model $table
113+
* @param array $values
114+
* @param string $index
115+
* @param string|null $index2
116+
* @param bool $raw
117+
* @return bool|int
118+
* @updatedBy Ibrahim Sakr <ebrahimes@gmail.com>
119+
*
120+
* @desc
121+
* Example
122+
* $table = 'users';
123+
* $value = [
124+
* [
125+
* 'id' => 1,
126+
* 'status' => 'active',
127+
* 'nickname' => 'Mohammad'
128+
* ] ,
129+
* [
130+
* 'id' => 5,
131+
* 'status' => 'deactive',
132+
* 'nickname' => 'Ghanbari'
133+
* ] ,
134+
* ];
135+
* $index = 'id';
136+
* $index2 = 'user_id';
137+
*
138+
*/
139+
public function updateWithTwoIndex(Model $table, array $values, string $index = null, string $index2 = null, bool $raw = false)
140+
{
141+
$final = [];
142+
$ids = [];
143+
144+
if (!count($values)) {
145+
return false;
146+
}
147+
148+
if (!isset($index) || empty($index)) {
149+
$index = $table->getKeyName();
150+
}
151+
152+
foreach ($values as $key => $val) {
153+
$ids[] = $val[$index];
154+
$ids2[] = $val[$index2];
155+
foreach (array_keys($val) as $field) {
156+
if ($field !== $index || $field !== $index2 ) {
157+
$finalField = $raw ? Common::mysql_escape($val[$field]) : '"' . Common::mysql_escape($val[$field]) . '"';
158+
$value = (is_null($val[$field]) ? 'NULL' : $finalField);
159+
$final[$field][] = 'WHEN (`' . $index . '` = "' . Common::mysql_escape($val[$index]) .'" AND `'. $index2 . '` = "' . $val[$index2] .'") THEN ' . $value . ' ';
160+
}
161+
}
162+
}
163+
164+
$cases = '';
165+
foreach ($final as $k => $v) {
166+
$cases .= '`' . $k . '` = (CASE ' . implode("\n", $v) . "\n"
167+
. 'ELSE `' . $k . '` END), ';
168+
}
169+
$query = "UPDATE `" . $this->getFullTableName($table) . "` SET " . substr($cases, 0, -2) . " WHERE `$index` IN(" . '"' . implode('","', $ids) . '")' . " AND `$index2` IN(" . '"' . implode('","', $ids2) . '"' ." );";
170+
171+
return $this->db->connection($this->getConnectionName($table))->update($query);
172+
}
173+
110174
/**
111175
* Insert Multi rows.
112176
*

0 commit comments

Comments
 (0)