Reputation: 415
how to write rules for two tables in one model yii2, my code is:
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.
Upvotes: 0
Views: 780
Reputation: 22609
That's close to impossible.
Doing this would not be a good idea, and there is a better way. Each ActiveRecord model is responsible for just one table. 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. 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.
Upvotes: 1
Reputation: 136
You can simply write the rules in the model and change tableName property if you want to use different table. I would also recommend using scenarios. More here: https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-models.md.
Upvotes: 0