Skip to content

Commit

Permalink
add method update Multiple Condition.
Browse files Browse the repository at this point in the history
  • Loading branch information
mavinoo committed Jul 14, 2024
1 parent d931f44 commit 133e278
Show file tree
Hide file tree
Showing 3 changed files with 194 additions and 13 deletions.
57 changes: 52 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,64 @@
# Laravel BATCH (BULK)

Insert and update batch (bulk) in laravel

[![License](https://poser.pugx.org/mavinoo/laravel-batch/license)](https://packagist.org/packages/mavinoo/laravel-batch)
[![Latest Stable Version](https://poser.pugx.org/mavinoo/laravel-batch/v/stable)](https://packagist.org/packages/mavinoo/laravel-batch)
[![Total Downloads](https://poser.pugx.org/mavinoo/laravel-batch/downloads)](https://packagist.org/packages/mavinoo/laravel-batch)
[![Daily Downloads](https://poser.pugx.org/mavinoo/laravel-batch/d/daily)](https://packagist.org/packages/mavinoo/laravel-batch)


# Install

`composer require mavinoo/laravel-batch`

# Service Provider

file app.php in array providers :

`Mavinoo\Batch\BatchServiceProvider::class,`

# Aliases

file app.php in array aliases :

`'Batch' => Mavinoo\Batch\BatchFacade::class,`

# Example Update 1
# Example Update Multiple Condition

```php
use App\Models\User;

$userInstance = new User;
$arrays = [
[
'conditions' => ['id' => 1, 'status' => 'active'],
'columns' => [
'status' => 'invalid'
'nickname' => 'mohammad'
],
],
[
'conditions' => ['id' => 2],
'columns' => [
'nickname' => 'mavinoo',
'name' => 'mohammad',
],
],
[
'conditions' => ['id' => 3],
'columns' => [
'nickname' => 'ali'
],
],
];
$keyName = 'id';

Batch::updateMultipleCondition($userInstance, $arrays, $keyName);
or
batch()->updateMultipleCondition($userInstance, $arrays, $keyName);
```

# Example Update 2

```php
use App\Models\User;
Expand All @@ -41,9 +79,11 @@ $value = [
$index = 'id';

Batch::update($userInstance, $value, $index);
or
batch()->update($userInstance, $values, $index);
```

# Example Update 2
# Example Update 3

```php
use App\Models\User;
Expand Down Expand Up @@ -72,6 +112,8 @@ $value = [
$index = 'id';

Batch::update($userInstance, $value, $index);
or
batch()->update($userInstance, $values, $index);
```

# Example Increment / Decrement
Expand Down Expand Up @@ -105,6 +147,8 @@ $value = [
$index = 'id';

Batch::update($userInstance, $value, $index);
or
batch()->update($userInstance, $values, $index);
```

# Example Insert
Expand Down Expand Up @@ -146,9 +190,10 @@ $values = [
$batchSize = 500; // insert 500 (default), 100 minimum rows in one query

$result = Batch::insert($userInstance, $columns, $values, $batchSize);
or
$result = batch()->insert($userInstance, $values, $index);
```


```php
// result : false or array

Expand Down Expand Up @@ -202,9 +247,11 @@ $result = batch()->insert($userInstance, $columns, $values, $batchSize);
```

# Tests

If you don't have phpunit installed on your project, first run `composer require phpunit/phpunit`

In the root of your laravel app, run `./vendor/bin/phpunit ./vendor/mavinoo/laravel-batch/tests`

# Donate
# Donate

USDT Address: 0x98410956169cdd00a43fe895303bdca096f37062
139 changes: 131 additions & 8 deletions src/Batch.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public function __construct(DatabaseManager $db)
* @param string $index
* @param bool $raw
* @return bool|int
* @createdBy Mohammad Ghanbari <[email protected]>
* @updatedBy Ibrahim Sakr <[email protected]>
*/
public function update(Model $table, array $values, string $index = null, bool $raw = false)
Expand Down Expand Up @@ -119,7 +120,7 @@ public function update(Model $table, array $values, string $index = null, bool $
$cases = '';
foreach ($final as $k => $v) {
$cases .= '"' . $k . '" = (CASE ' . implode("\n", $v) . "\n"
. 'ELSE "' . $k . '" END), ';
. 'ELSE "' . $k . '" END), ';
}

$query = "UPDATE \"" . $this->getFullTableName($table) . '" SET ' . substr($cases, 0, -2) . " WHERE \"$index\" IN('" . implode("','", $ids) . "');";
Expand All @@ -129,14 +130,13 @@ public function update(Model $table, array $values, string $index = null, bool $
$cases = '';
foreach ($final as $k => $v) {
$cases .= '`' . $k . '` = (CASE ' . implode("\n", $v) . "\n"
. 'ELSE `' . $k . '` END), ';
. 'ELSE `' . $k . '` END), ';
}

$query = "UPDATE `" . $this->getFullTableName($table) . "` SET " . substr($cases, 0, -2) . " WHERE `$index` IN(" . '"' . implode('","', $ids) . '"' . ");";

}


return $this->db->connection($this->getConnectionName($table))->update($query);
}

Expand All @@ -148,6 +148,7 @@ public function update(Model $table, array $values, string $index = null, bool $
* @param string|null $index2
* @param bool $raw
* @return bool|int
* @createdBy Mohammad Ghanbari <[email protected]>
* @updatedBy Ibrahim Sakr <[email protected]>
*
* @desc
Expand Down Expand Up @@ -205,7 +206,7 @@ public function updateWithTwoIndex(Model $table, array $values, string $index =
$cases = '';
foreach ($final as $k => $v) {
$cases .= '"' . $k . '" = (CASE ' . implode("\n", $v) . "\n"
. 'ELSE "' . $k . '" END), ';
. 'ELSE "' . $k . '" END), ';
}

$query = "UPDATE \"" . $this->getFullTableName($table) . '" SET ' . substr($cases, 0, -2) . " WHERE \"$index\" IN('" . implode("','", $ids) . "') AND \"$index2\" IN('" . implode("','", $ids2) . "');";
Expand All @@ -214,14 +215,135 @@ public function updateWithTwoIndex(Model $table, array $values, string $index =
$cases = '';
foreach ($final as $k => $v) {
$cases .= '`' . $k . '` = (CASE ' . implode("\n", $v) . "\n"
. 'ELSE `' . $k . '` END), ';
. 'ELSE `' . $k . '` END), ';
}
$query = "UPDATE `" . $this->getFullTableName($table) . "` SET " . substr($cases, 0, -2) . " WHERE `$index` IN(" . '"' . implode('","', $ids) . '")' . " AND `$index2` IN(" . '"' . implode('","', $ids2) . '"' . " );";
}

return $this->db->connection($this->getConnectionName($table))->update($query);
}

/**
* Update multiple condition rows
* @param Model $table
* @param array $arrays
* @param string $keyName
* @param bool $raw
* @return bool|int
* @createdBy Mohammad Ghanbari <[email protected]>
*
* @desc
* Example
* $table = new \App\Models\User;
* $arrays = [
* [
* 'conditions' => ['id' => 1, 'status' => 'active'],
* 'columns' => [
* 'status' => 'invalid'
* 'nickname' => 'mohammad'
* ],
* ],
* [
* 'conditions' => ['id' => 2],
* 'columns' => [
* 'nickname' => 'mavinoo',
* 'name' => 'mohammad',
* ],
* ],
* [
* 'conditions' => ['id' => 3],
* 'columns' => [
* 'nickname' => 'ali'
* ],
* ],
* ];
* $keyName = 'id';
*
*/
public function updateMultipleCondition(Model $table, array $arrays, string $keyName = null, bool $raw = false)
{
$driver = $table->getConnection()->getDriverName();
$connectionName = $this->getConnectionName($table);
$tableName = $this->getFullTableName($table);
$timestamp = $table->usesTimestamps();
$backtick = Common::disableBacktick($driver) ? '`' : '';

if (!count($arrays)) {
return false;
}

if (!isset($keyName) || empty($keyName)) {
$keyName = $table->getKeyName();
}

$columns = [];
$conditionMaster = [];
foreach ($arrays as $array) {
foreach ($array['conditions'] as $keyCondition => $condition) {
if ($keyName == $keyCondition and !in_array($condition, $conditionMaster)) {
$conditionMaster[] = str(Common::mysql_escape($condition))->toString();
}
}
foreach ($array as $key => $item) {
if ($key == 'columns') {
foreach ($item as $k => $value) {
if (!in_array($key, $columns)) {
$columns[$k] = $k;
}
}
}
}
}

$arraysNew = [];
$keys = array_keys($columns);
foreach ($keys as $key) {
$arraysMixed = collect($arrays)->filter(function ($rows) use ($key) {
return in_array($key, array_keys($rows['columns']));
});

foreach ($arraysMixed as $item) {
$value = $raw ? Common::mysql_escape($item['columns'][$key]) : "'" . Common::mysql_escape($item['columns'][$key]) . "'";
$arraysNew[$key][] = [
'conditions' => $item['conditions'],
'value' => is_null($item['columns'][$key]) ? "NULL" : $value,
];

if ($timestamp) {
$arraysNew['updated_at'][] = [
'conditions' => $item['conditions'],
'value' => "'".(now())."'",
];
}
}
}

$cases = [];
foreach ($arraysNew as $key => $items) {
$caseSql = "{$backtick}{$key}{$backtick} = (CASE ";
foreach ($items as $item) {
$conditions = $item['conditions'];
$value = $item['value'];

$conditionContext = [];
foreach ($conditions as $conditionKey => $condition) {
$conditionContext[] = " {$backtick}{$conditionKey}{$backtick} = '{$condition}' ";
}

$conditionContext = join(' and ', $conditionContext);
$caseSql .= " WHEN $conditionContext THEN {$value} ";
}
$caseSql .= " ELSE {$backtick}{$key}{$backtick} END)";
$cases[] = $caseSql;
}
$caseSql = join(', ', $cases);
$conditionMaster = join(', ', $conditionMaster);

$query = "update {$backtick}{$tableName}{$backtick} set {$caseSql} where {$backtick}{$keyName}{$backtick} in ({$conditionMaster})";

return $this->db->connection($connectionName)->update($query);
}

/**
* Insert Multi rows.
*
Expand All @@ -232,6 +354,7 @@ public function updateWithTwoIndex(Model $table, array $values, string $index =
* @param bool $insertIgnore
* @return bool|mixed
* @throws \Throwable
* @createdBy Mohammad Ghanbari <[email protected]>
* @updatedBy Ibrahim Sakr <[email protected]>
* @desc
* Example
Expand Down Expand Up @@ -360,9 +483,9 @@ public function insert(Model $table, array $columns, array $values, int $batchSi
}

return [
'totalRows' => $totalValues,
'totalBatch' => $totalChunk,
'totalQuery' => $totalQuery
'totalRows' => $totalValues,
'totalBatch' => $totalChunk,
'totalQuery' => $totalQuery
];
});
}
Expand Down
11 changes: 11 additions & 0 deletions src/BatchInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ public function update(Model $table, array $values, string $index = null, bool $
*/
public function updateWithTwoIndex(Model $table, array $values, string $index = null, string $index2 = null, bool $raw = false);

/**
* Update multiple condition rows.
*
* @param Model $table
* @param array $values
* @param string|null $index
* @param bool $raw
* @return mixed
*/
public function updateMultipleCondition(Model $table, array $values, string $index = null, bool $raw = false);

/**
* Insert multiple rows.
*
Expand Down

0 comments on commit 133e278

Please sign in to comment.