Php Yii2表单更新-基于相关模型属性的验证

Php Yii2表单更新-基于相关模型属性的验证,php,validation,yii2,sql-update,foreign-keys,Php,Validation,Yii2,Sql Update,Foreign Keys,我有一个表单,其中第一步是选择城市(城市是一个相关模型,具有人口最小值和最大值属性,例如10.000-12.000)。在第二步中,用户必须填写人口(如11.000)。现在,在规则中,我检查用户是否填写了正确的人口数量(如果在城市的最小人口和最大人口之间)。 创建新记录正在工作。但我对更新操作有问题。因为如果我已经有一个人口数字(11.000)并且我有一个城市,并且我想将城市更改为人口应该在5.000和7.000之间的其他地方,我的模型中的人口验证将失败,因为它是基于旧城市进行验证的(当然,在所有

我有一个表单,其中第一步是选择城市(城市是一个相关模型,具有人口最小值和最大值属性,例如10.000-12.000)。在第二步中,用户必须填写人口(如11.000)。现在,在规则中,我检查用户是否填写了正确的人口数量(如果在城市的最小人口和最大人口之间)。 创建新记录正在工作。但我对更新操作有问题。因为如果我已经有一个人口数字(11.000)并且我有一个
城市
,并且我想将城市更改为人口应该在5.000和7.000之间的其他地方,我的模型中的人口验证将失败,因为它是基于旧城市进行验证的(当然,在所有值通过验证之前,
city\u id
不会更新)。您能告诉我正确的方向吗?我是否应该在验证之前更新模型中的
city\u id
(可能吗)?谢谢

表格:


示范规则:

...
['population', 'validatePopulation'],
...

public function getCity() {
    return $this->hasOne(\app\models\City::className(), ['id' => 'city_id']);
}

public function validatePopulation($attribute, $params, $validator) {
    if ($this->population < $this->city->population_min) {
        $this->addError($attribute, 'Population has to be larger than ' . $this->city->population_min);
    } elseif ($this->population > $this->city->population_max) {
        $this->addError($attribute, 'Population has to be smaller than ' . $this->city->population_max);
    }
}
。。。
['population','validatePopulation'],
...
公共功能getCity(){
返回$this->hasOne(\app\models\City::className(),['id'=>'City\u id']);
}
公共函数validatePopulation($attribute、$params、$validator){
如果($this->population<$this->city->population\u min){
$this->addError($attribute,“人口必须大于”。$this->city->Population\u min);
}elseif($this->population>$this->city->population\u max){
$this->addError($attribute,“人口必须小于”。$this->city->Population_max);
}
}

您可以在服务器端验证中进行检查,这意味着当用户发布数据时,您可以检查控制器城市id和人口。添加一些代码,尤其是模型规则和表单
...
['population', 'validatePopulation'],
...

public function getCity() {
    return $this->hasOne(\app\models\City::className(), ['id' => 'city_id']);
}

public function validatePopulation($attribute, $params, $validator) {
    if ($this->population < $this->city->population_min) {
        $this->addError($attribute, 'Population has to be larger than ' . $this->city->population_min);
    } elseif ($this->population > $this->city->population_max) {
        $this->addError($attribute, 'Population has to be smaller than ' . $this->city->population_max);
    }
}