|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Mavinoo\Batch\Traits; |
| 4 | + |
| 5 | +use Mavinoo\Batch\Batch; |
| 6 | + |
| 7 | +trait HasBatch |
| 8 | +{ |
| 9 | + /** |
| 10 | + * Update multiple rows. |
| 11 | + * |
| 12 | + * Example: |
| 13 | + * ``` |
| 14 | + * use App\Models\User; |
| 15 | + * |
| 16 | + * $values = [ |
| 17 | + * [ |
| 18 | + * 'id' => 1, |
| 19 | + * 'status' => 'active', |
| 20 | + * 'nickname' => 'Mohammad', |
| 21 | + * ], |
| 22 | + * [ |
| 23 | + * 'id' => 5, |
| 24 | + * 'status' => 'deactive', |
| 25 | + * 'nickname' => 'Ghanbari', |
| 26 | + * ], |
| 27 | + * [ |
| 28 | + * 'id' => 7, |
| 29 | + * 'balance' => ['+', 500], |
| 30 | + * ], |
| 31 | + * ]; |
| 32 | + * |
| 33 | + * User::batchUpdate($values, 'id'); |
| 34 | + * ``` |
| 35 | + * |
| 36 | + * @param array $values |
| 37 | + * @param string|null $index |
| 38 | + * @param bool $raw |
| 39 | + * @return bool|int |
| 40 | + */ |
| 41 | + public static function batchUpdate(array $values, string $index = null, bool $raw = false) |
| 42 | + { |
| 43 | + return app(Batch::class)->update(new static, $values, $index, $raw); |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Insert multiple rows. |
| 48 | + * |
| 49 | + * Example: |
| 50 | + * ``` |
| 51 | + * use App\Models\User; |
| 52 | + * |
| 53 | + * $columns = [ |
| 54 | + * 'firstName', |
| 55 | + * 'lastName', |
| 56 | + * 'email', |
| 57 | + * 'isActive', |
| 58 | + * 'status', |
| 59 | + * ]; |
| 60 | + * $values = [ |
| 61 | + * [ |
| 62 | + * 'Mohammad', |
| 63 | + * 'Ghanbari', |
| 64 | + |
| 65 | + * '1', |
| 66 | + * '0', |
| 67 | + * ] , |
| 68 | + * [ |
| 69 | + * 'Saeed', |
| 70 | + * 'Mohammadi', |
| 71 | + |
| 72 | + * '1', |
| 73 | + * '0', |
| 74 | + * ] , |
| 75 | + * [ |
| 76 | + * 'Avin', |
| 77 | + * 'Ghanbari', |
| 78 | + |
| 79 | + * '1', |
| 80 | + * '0', |
| 81 | + * ] , |
| 82 | + * ]; |
| 83 | + * $batchSize = 500; // insert 500 (default), 100 minimum rows in one query |
| 84 | + * |
| 85 | + * User::batchInsert($columns, $values, $batchSize); |
| 86 | + * ``` |
| 87 | + * |
| 88 | + * @param array $columns |
| 89 | + * @param array $values |
| 90 | + * @param int $batchSize |
| 91 | + * @param bool $insertIgnore |
| 92 | + * @return bool|array |
| 93 | + */ |
| 94 | + public static function batchInsert(array $columns, array $values, int $batchSize = 500, bool $insertIgnore = false) |
| 95 | + { |
| 96 | + return app(Batch::class)->insert(new static, $columns, $values, $batchSize, $insertIgnore); |
| 97 | + } |
| 98 | +} |
0 commit comments