during validation I would like to compare with an attribute from another model. Is it possible? If yes, I would be grateful if you would point me to the right direction. I imagine it somehow to access model B in model A, but maybe my logic is not good, and I have no clue how can this be achieved. Thanks.
问题:
回答1:
You can try to build an inline validator see this doc for validator and for inline validator
this is a brief sample
public function rules() { return [ ..... ['my_field', 'validateMyCompare'], .... ]; } public function validateMyCompare($attribute, $params) { if (YourModel::findOne(['your_model_field'=> $attribute]) { $this->addError($attribute, \Yii::t('view', 'The fields don't match.')); } }
回答2:
I've solved it this way:
public function getRelatedmodel() { return $this->hasOne(\app\models\Relatedmodel::className(), ['id' => 'relatedId']); } public function getMotherRelatedAttribute() { if ($mother = Model::findOne($this->mother)) { return $mother->relatedmodel->attribute; } }
And in rules:
['attribute', 'compare', 'compareAttribute' => 'MotherRelatedAttribute', 'operator' => '<=', 'on' => self::SCENARIO_CREATE_RST],
回答3:
compare
[ // validates if the value of "password" attribute equals to that of "password_repeat" ['password', 'compare'], // validates if age is greater than or equal to 30 ['age', 'compare', 'compareValue' => 30, 'operator' => '>='], ]
This validator compares the specified input value with another one and make sure if their relationship is as specified by the operator property.
compareAttribute: the name of the attribute whose value should be compared with. When the validator is being used to validate an attribute, the default value of this property would be the name of the attribute suffixed with _repeat. For example, if the attribute being validated is password, then this property will default to password_repeat. compareValue: a constant value that the input value should be compared with. When both of this property and compareAttribute are specified, this property will take precedence. operator: the comparison operator. Defaults to ==, meaning checking if the input value is equal to that of compareAttribute or compareValue. The following operators are supported: ==: check if two values are equal. The comparison is done is non-strict mode. ===: check if two values are equal. The comparison is done is strict mode. !=: check if two values are NOT equal. The comparison is done is non-strict mode. !==: check if two values are NOT equal. The comparison is done is strict mode.
: check if value being validated is greater than the value being compared with. =: check if value being validated is greater than or equal to the value being compared with. <: check if value being validated is less than the value being compared with. <=: check if value being validated is less than or equal to the value being compared with.