在 Yii 中验证相关模型的属性 [英] Validate property of related model in Yii

查看:48
本文介绍了在 Yii 中验证相关模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Yii 中有四个模型.汽车、赛车、豪华车和司机.

I have four models in Yii. Car, RaceCar, LuxuryCar, and Driver.

RaceCar has_one Driver

RaceCar has_one Driver

LuxuryCar has_one Driver

LuxuryCar has_one Driver

RaceCar 和 LuxuryCar 都继承自同一个模型 - Car - 使用相同的表继承.

Both RaceCar and LuxuryCar inherit from the same model - Car - using same table inheritance.

LuxuryCar 和 RaceCar 中都有一个fuel_level"属性会改变 Driver 中的验证规则(如果 RaceCar.fuel_level 为零,Driver 不应将属性action"设置为driving").

There is a "fuel_level" attribute in both LuxuryCar and RaceCar that changes the validation rules in Driver (Driver should not be able to set attribute "action" to "driving" if RaceCar.fuel_level is zero).

而不是必须添加所有可能的属于"与 Driver 的关系(我可能会添加更多继承的 Car 模型),然后检查 Driver 当前属于哪种汽车,以便我可以加载模型再次从数据库中,我希望能够验证父级(例如 RaceCar)中 Driver 属性的值.

Rather than have to add every possible "belongs to" relation to Driver (I'm likely to add more inherited Car models), and then checking to see which kind of Car the Driver currently belongs to so I can load the model from the database again, I'd like to be able to validate the values of Driver's properties in the parent (e.g. RaceCar).

这可能吗?如果是这样,如何?如果没有,有没有更好的方法让我错过?

Is this possible? If so, how? If not, is there a better way that I'm missing?

推荐答案

一种解决方案是简单地为汽车的 driver 属性添加自定义(例如内联)验证规则:

One solution would be to simply add custom (e.g. inline) validation rules for the driver attribute of your cars:

public function rules() {
    return array('driver', 'validateDriver');
}

public function validateDriver() {
    if (!$this->driver->isFoo) {
        $this->addError('driver', Yii::t('validation', '{attribute} is not foo!'));
    }
}

这篇关于在 Yii 中验证相关模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆