简体   繁体   English

在一个模型yii2中为两个表编写规则

[英]write rules for two tables in one model yii2

how to write rules for two tables in one model yii2, my code is: 如何在一个模型yii2中为两个表编写规则,我的代码是:

public function rules()
{
    return [

        [['class_id', 'section'], 'required'],

        [['class_id', 'active'], 'integer'],

        [['section'], 'string', 'max' => 20]

    ];
}

This is for one table, how I can write these rules for more than one table in single module. 这是针对一个表的,如何在单个模块中为多个表编写这些规则。

Thanks in advance. 提前致谢。

Short answer 简短答案

That's close to impossible. 那几乎是不可能的。

Potentially helpful answer 可能有帮助的答案

Doing this would not be a good idea, and there is a better way. 这样做不是一个好主意,并且有更好的方法。 Each ActiveRecord model is responsible for just one table. 每个ActiveRecord模型仅负责一个表。 The single responsibility principle dictates, that it shouldn't interfere with things managed by classes. 单一责任原则规定,它不应干扰由类管理的事物。 So letting the model validate rules for a different table would violate that principle. 因此,让模型验证其他表的规则将违反该原则。

A better way to handle the situation would be to create a new model ( yii\\base\\Model , not ActiveRecord), which then would handle the input. 处理这种情况的更好方法是创建一个新模型( yii\\base\\Model ,而不是ActiveRecord),然后将处理输入。 It should delegate part of the validation to the active record models, but may add additional validation on its own. 它应该将部分验证委派给活动记录模型,但可以自己添加其他验证。 That model could also set different scenarios, depending on the input. 该模型还可以根据输入设置不同的方案。 That way, you get a clean separation of responsibilities between models. 这样,您就可以将模型之间的职责完全分开。

You can simply write the rules in the model and change tableName property if you want to use different table. 如果要使用其他表,则可以简单地在模型中编写规则并更改tableName属性。 I would also recommend using scenarios. 我还建议使用方案。 More here: https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-models.md . 更多内容请参见: https : //github.com/yiisoft/yii2/blob/master/docs/guide/structure-models.md

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM