@@ -19,30 +19,37 @@ public function __construct(DatabaseManager $db)
1919 }
2020
2121 /**
22- * Update multiple rows.
22+ * <h2> Update multiple rows.</h2>
2323 *
24- * @param Model $table
25- * @param array $values
26- * @param string $index
27- * @param bool $raw
28- * @return bool|int
29- * @updatedBy Ibrahim Sakr <ebrahimes@gmail.com>
30- * @desc
31- * Example
32- * $table = 'users';
24+ * Example:<br>
25+ * ```
26+ * $userInstance = new \App\Models\User;
3327 * $value = [
3428 * [
3529 * 'id' => 1,
3630 * 'status' => 'active',
3731 * 'nickname' => 'Mohammad'
38- * ] ,
32+ * ],
3933 * [
4034 * 'id' => 5,
4135 * 'status' => 'deactive',
4236 * 'nickname' => 'Ghanbari'
43- * ] ,
37+ * ],
38+ * [
39+ * 'id' => 7,
40+ * 'balance' => ['+', 500]
41+ * ]
4442 * ];
4543 * $index = 'id';
44+ * Batch::update($userInstance, $value, $index);
45+ * ```
46+ *
47+ * @param \Illuminate\Database\Eloquent\Model $table
48+ * @param array $values
49+ * @param string $index
50+ * @param bool $raw
51+ * @return bool|int
52+ * @updatedBy Ibrahim Sakr <ebrahimes@gmail.com>
4653 */
4754 public function update (Model $ table , array $ values , string $ index = null , bool $ raw = false )
4855 {
@@ -73,12 +80,28 @@ public function update(Model $table, array $values, string $index = null, bool $
7380
7481 foreach (array_keys ($ val ) as $ field ) {
7582 if ($ field !== $ index ) {
76- if (gettype ($ val [$ field ]) == 'string ' && !empty ($ val [$ field ]) && str_replace (['+ ' , '- ' , '* ' , '/ ' , '% ' ], '' , $ val [$ field ][0 ]) !== $ val [$ field ][0 ]) {
77- $ value = '` ' . $ field . '` ' . $ val [$ field ];
83+ // If increment / decrement
84+ if (gettype ($ val [$ field ]) == 'array ' ) {
85+ // If array has two values
86+ if (!array_key_exists (0 , $ val [$ field ]) || !array_key_exists (1 , $ val [$ field ])) {
87+ throw new \ArgumentCountError ('Increment/Decrement array needs to have 2 values, a math operator (+, -, *, /, %) and a number ' );
88+ }
89+ // Check first value
90+ if (gettype ($ val [$ field ][0 ]) != 'string ' || !in_array ($ val [$ field ][0 ], ['+ ' , '- ' , '* ' , '/ ' , '% ' ])) {
91+ throw new \TypeError ('First value in Increment/Decrement array needs to be a string and a math operator (+, -, *, /, %) ' );
92+ }
93+ // Check second value
94+ if (!is_numeric ($ val [$ field ][1 ])) {
95+ throw new \TypeError ('Second value in Increment/Decrement array needs to be numeric ' );
96+ }
97+ // Increment / decrement
98+ $ value = '` ' . $ field . '` ' . $ val [$ field ][0 ] . $ val [$ field ][1 ];
7899 } else {
100+ // Only update
79101 $ finalField = $ raw ? Common::mysql_escape ($ val [$ field ]) : "' " . Common::mysql_escape ($ val [$ field ]) . "' " ;
80102 $ value = (is_null ($ val [$ field ]) ? 'NULL ' : $ finalField );
81103 }
104+
82105 if ($ driver == 'pgsql ' )
83106 $ final [$ field ][] = 'WHEN ' . $ index . ' = \'' . $ val [$ index ] . '\' THEN ' . $ value . ' ' ;
84107 else
0 commit comments