Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize yii\validators\ExistValidator #18806

Merged
merged 2 commits into from
Aug 6, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions framework/validators/ExistValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,13 @@ private function checkTargetRelationExistence($model, $attribute)
$relationQuery->andWhere($this->filter);
}

if ($this->forceMasterDb && method_exists($model::getDb(), 'useMaster')) {
$model::getDb()->useMaster(function() use ($relationQuery, &$exists) {
$exists = $relationQuery->exists();
});
$connection = $model::getDb();
if ($this->forceMasterDb && method_exists($connection, 'useMaster')) {
$exists = $connection->useMaster([$relationQuery, 'exists']);
} else {
$exists = $relationQuery->exists();
}


if (!$exists) {
$this->addError($model, $attribute, $this->message);
}
Expand Down Expand Up @@ -246,9 +244,9 @@ protected function validateValue($value)
}

/**
* Check whether value exists in target table
* Check whether value exists in target table.
*
* @param string $targetClass
* @param string $targetClass the model
* @param QueryInterface $query
* @param mixed $value the value want to be checked
* @return bool
Expand All @@ -259,8 +257,8 @@ private function valueExists($targetClass, $query, $value)
$exists = false;

if ($this->forceMasterDb && method_exists($db, 'useMaster')) {
$db->useMaster(function ($db) use ($query, $value, &$exists) {
$exists = $this->queryValueExists($query, $value);
$exists = $db->useMaster(function () use ($query, $value) {
return $this->queryValueExists($query, $value);
});
} else {
$exists = $this->queryValueExists($query, $value);
Expand All @@ -271,7 +269,7 @@ private function valueExists($targetClass, $query, $value)


/**
* Run query to check if value exists
* Run query to check if value exists.
*
* @param QueryInterface $query
* @param mixed $value the value to be checked
Expand All @@ -280,7 +278,7 @@ private function valueExists($targetClass, $query, $value)
private function queryValueExists($query, $value)
{
if (is_array($value)) {
return $query->count("DISTINCT [[$this->targetAttribute]]") == count(array_unique($value)) ;
return $query->count("DISTINCT [[$this->targetAttribute]]") == count(array_unique($value));
}
return $query->exists();
}
Expand Down