Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 rules compareAttribute compare with attribute of another model

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.

like image 449
user2511599 Avatar asked Dec 07 '25 05:12

user2511599


1 Answers

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],
like image 192
user2511599 Avatar answered Dec 11 '25 03:12

user2511599



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!