|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Thinktomorrow\AssetLibrary\Application; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Facades\DB; |
|
6
|
|
|
use Thinktomorrow\AssetLibrary\Asset; |
|
7
|
|
|
use Thinktomorrow\AssetLibrary\HasAsset; |
|
8
|
|
|
|
|
9
|
|
|
class ReorderAssets |
|
10
|
|
|
{ |
|
11
|
|
|
public function handle(HasAsset $model, string $type, string $locale, array $orderedAssetIds): void |
|
12
|
|
|
{ |
|
13
|
|
|
$model->assetRelation() |
|
14
|
|
|
->where('assets_pivot.type', $type) |
|
15
|
|
|
->where('assets_pivot.locale', $locale) |
|
16
|
|
|
->get() |
|
17
|
|
|
->each(function(Asset $asset) use($model, $orderedAssetIds, $type, $locale){ |
|
18
|
|
|
|
|
19
|
|
|
DB::table('assets_pivot') |
|
20
|
|
|
->where('asset_id', $asset->id) |
|
21
|
|
|
->where('entity_type', $model->getMorphClass()) |
|
|
|
|
|
|
22
|
|
|
->where('entity_id', $model->getKey()) |
|
|
|
|
|
|
23
|
|
|
->where('type', $type) |
|
24
|
|
|
->where('locale', $locale) |
|
25
|
|
|
->update([ |
|
26
|
|
|
'order' => array_search($asset->id, $orderedAssetIds), |
|
27
|
|
|
]); |
|
28
|
|
|
}); |
|
29
|
|
|
|
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Taken from: https://github.com/laravel/ideas/issues/575 |
|
34
|
|
|
* |
|
35
|
|
|
* @return void |
|
36
|
|
|
*/ |
|
37
|
|
|
private static function batchUpdateColumn(string $table, string $column, array $indices, string $indexColumn = 'id', bool $castIdToIntegers = true, string $extraWhere = null): void |
|
|
|
|
|
|
38
|
|
|
{ |
|
39
|
|
|
$cases = []; |
|
40
|
|
|
$ids = []; |
|
41
|
|
|
$params = []; |
|
42
|
|
|
|
|
43
|
|
|
foreach ($indices as $index => $modelId) { |
|
44
|
|
|
$id = $castIdToIntegers ? (int) $modelId : $modelId; |
|
45
|
|
|
$ids[] = "'{$id}'"; |
|
46
|
|
|
|
|
47
|
|
|
$cases[] = "WHEN '{$id}' then ?"; |
|
48
|
|
|
$params[] = $index; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$ids = implode(',', $ids); |
|
52
|
|
|
$cases = implode(' ', $cases); |
|
53
|
|
|
|
|
54
|
|
|
if ($extraWhere) { |
|
55
|
|
|
$extraWhere = ' AND ' . DB::raw($extraWhere); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
DB::update("UPDATE `{$table}` SET `{$column}` = CASE `".$indexColumn."` {$cases} END WHERE `".$indexColumn."` in ({$ids})".$extraWhere, $params); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|