|
|
|
@ -9,6 +9,8 @@ namespace yii\validators;
|
|
|
|
|
|
|
|
|
|
use Yii; |
|
|
|
|
use yii\base\InvalidConfigException; |
|
|
|
|
use yii\base\Model; |
|
|
|
|
use yii\db\ActiveRecord; |
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* ExistValidator validates that the attribute value exists in a table. |
|
|
|
@ -137,14 +139,41 @@ class ExistValidator extends Validator
|
|
|
|
|
if ($this->allowArray) { |
|
|
|
|
throw new InvalidConfigException('The "targetAttribute" property must be configured as a string.'); |
|
|
|
|
} |
|
|
|
|
$params = []; |
|
|
|
|
$conditions = []; |
|
|
|
|
foreach ($targetAttribute as $k => $v) { |
|
|
|
|
$params[$v] = is_int($k) ? $model->$v : $model->$k; |
|
|
|
|
$conditions[$v] = is_int($k) ? $model->$v : $model->$k; |
|
|
|
|
} |
|
|
|
|
} else { |
|
|
|
|
$params = [$targetAttribute => $model->$attribute]; |
|
|
|
|
$conditions = [$targetAttribute => $model->$attribute]; |
|
|
|
|
} |
|
|
|
|
return $params; |
|
|
|
|
|
|
|
|
|
if (!$model instanceof ActiveRecord) { |
|
|
|
|
return $conditions; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
// Add table prefix for column |
|
|
|
|
$targetClass = $this->getTargetClass($model); |
|
|
|
|
|
|
|
|
|
/** @var ActiveRecord $targetClass */ |
|
|
|
|
$query = $targetClass::find(); |
|
|
|
|
$tableAliases = $query->getFromAliases(); |
|
|
|
|
$primaryTableAlias = $tableAliases[0]; |
|
|
|
|
$prefixedConditions = []; |
|
|
|
|
foreach ($conditions as $columnName => $columnValue) { |
|
|
|
|
$prefixedColumn = "{$primaryTableAlias}.{$columnName}"; |
|
|
|
|
$prefixedConditions[$prefixedColumn] = $columnValue; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return $prefixedConditions; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
* @param Model $model the data model to be validated |
|
|
|
|
* @return string Target class name |
|
|
|
|
*/ |
|
|
|
|
private function getTargetClass($model) |
|
|
|
|
{ |
|
|
|
|
return $this->targetClass === null ? get_class($model) : $this->targetClass; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|