Skip to content

Commit 64771c1

Browse files
authored
Merge pull request #44 from p4rse/master
maintain the created_at and updated_at columns automatically
2 parents d7f50c1 + 13b829d commit 64771c1

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/Batch.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,15 @@ public function update(Model $table, array $values, string $index = null, bool $
5959

6060
foreach ($values as $key => $val) {
6161
$ids[] = $val[$index];
62+
63+
if ($table->usesTimestamps()) {
64+
$updatedAtColumn = $table->getUpdatedAtColumn();
65+
66+
if (!isset($val[$updatedAtColumn])) {
67+
$val[$updatedAtColumn] = now()->format($table->getDateFormat());
68+
}
69+
}
70+
6271
foreach (array_keys($val) as $field) {
6372
if ($field !== $index) {
6473
$finalField = $raw ? Common::mysql_escape($val[$field]) : "'" . Common::mysql_escape($val[$field]) . "'";
@@ -163,6 +172,37 @@ public function insert(Model $table, array $columns, array $values, int $batchSi
163172

164173
$values = array_chunk($values, $totalChunk, true);
165174

175+
if ($table->usesTimestamps()) {
176+
$createdAtColumn = $table->getCreatedAtColumn();
177+
$updatedAtColumn = $table->getUpdatedAtColumn();
178+
$now = now()->format($table->getDateFormat());
179+
180+
$addCreatedAtValue = false;
181+
$addUpdatedAtValue = false;
182+
183+
if (!in_array($createdAtColumn, $columns)) {
184+
$addCreatedAtValue = true;
185+
array_push($columns, $createdAtColumn);
186+
}
187+
188+
if (!in_array($updatedAtColumn, $columns)) {
189+
$addUpdatedAtValue = true;
190+
array_push($columns, $updatedAtColumn);
191+
}
192+
193+
foreach ($values as $key => $value) {
194+
foreach ($value as $rowKey => $row) {
195+
if ($addCreatedAtValue) {
196+
array_push($values[$key][$rowKey], $now);
197+
}
198+
199+
if ($addUpdatedAtValue) {
200+
array_push($values[$key][$rowKey], $now);
201+
}
202+
}
203+
}
204+
}
205+
166206
foreach ($columns as $key => $column) {
167207
$columns[$key] = '`' . Common::mysql_escape($column) . '`';
168208
}

0 commit comments

Comments
 (0)