Skip to content

Commit 9282245

Browse files
authored
Optimize query
1 parent edf64c0 commit 9282245

1 file changed

Lines changed: 8 additions & 11 deletions

File tree

src/Models/Scopes/ForCurrentStoreWithoutLimitScope.php

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@ class ForCurrentStoreWithoutLimitScope implements Scope
1414
{
1515
public array $uniquePerStoreKeys;
1616

17-
public function __construct(string|array $uniquePerStoreKey, public $storeIdColumn = 'store_id')
18-
{
17+
public function __construct(string|array $uniquePerStoreKey, public $storeIdColumn = 'store_id') {
1918
$this->uniquePerStoreKeys = is_array($uniquePerStoreKey) ? $uniquePerStoreKey : [$uniquePerStoreKey];
2019
}
2120

@@ -35,18 +34,16 @@ public function apply(Builder $query, Model $model)
3534
->where(fn ($query) => $query
3635
// Remove values where we already have values in the current store.
3736
->where(function ($query) use ($scope, $model) {
38-
$columnKey = count($scope->uniquePerStoreKeys) === 1 ? $query->qualifyColumn($scope->uniquePerStoreKeys[0]) : DB::Raw('CONCAT(' . collect($scope->uniquePerStoreKeys)->map(fn ($key) => $query->qualifyColumn($key))->implode(",'-',") . ')');
39-
4037
$query
41-
->whereNotIn($columnKey, function ($query) use ($scope, $model, $columnKey) {
38+
->whereNotExists(function ($query) use ($scope, $model) {
4239
$query
43-
->select($columnKey)
44-
->from($model->getTable())
45-
->where($model->qualifyColumn($scope->storeIdColumn), config('rapidez.store'));
46-
foreach ($scope->uniquePerStoreKeys as $uniquePerStoreKey) {
47-
$query->whereColumn($model->qualifyColumn($uniquePerStoreKey), $model->qualifyColumn($uniquePerStoreKey));
40+
->select(DB::raw(1))
41+
->from($model->getTable() . ' as comparison')
42+
->where('comparison.'.$this->storeIdColumn, config('rapidez.store'));
43+
foreach($scope->uniquePerStoreKeys as $uniquePerStoreKey) {
44+
$query->whereColumn('comparison.'.$uniquePerStoreKey, $model->qualifyColumn($uniquePerStoreKey));
4845
}
49-
});
46+
});
5047
})
5148
// Unless the value IS the current store.
5249
->orWhere($query->qualifyColumn($this->storeIdColumn), config('rapidez.store'))

0 commit comments

Comments
 (0)