[英]How to check if any of the fields of a model are null or empty?
我有一个模型, $userModel
。 我想检查此模型的任何字段是空还是null
。
目前我正在做一个很大的if声明。
if(!empty($userModel->name) && !empty($userModel->address) ... && !empty($userModel->email))
{
// All fields have values
}
这种方式有效,但如果以后我需要在模型中添加另一个字段,那么我需要回到if并在那里添加另一个&&
条件。
我怎么能在一张支票上做到这一点?
有类似的东西: $userModel::model()->areAllFieldsFilled();
额外信息:模型已保存在数据库中,无需用户输入。 这只是我检查特定模型的完整程度,绝不会在数据库中只需要几个字段。 像$userModel->bio
这样的东西通常都是null
。
我想避免检查5到10个字段。 如果在模型改变时必须维护,我不想要一个巨人。
使用empty()
if(!empty($userModel->name)) { .. }
更新
$modelData = array($userModel->name, $userModel->address, $userModel->email);
if(!in_array('', $modelData) && !in_array(null, $modelData)) { .. }
或者你可以使用array_intersect
-
if(empty(array_intersect(array('', null), $modelData))) { .. }
我想你不需要这样做。
您需要的一切 - 它只是指定您的验证规则。
例如:
<?php
class Brand extends CActiveRecord
{
public function tableName()
{
return 'brand';
}
public function rules()
{
return [
['name, country', 'on' => 'insert'],
['name', 'type', 'type' => 'string', 'on' => 'insert'],
['name', 'length', 'max' => 100, 'on' => 'insert'],
['name', 'type', 'type' => 'array', 'on' => 'search'],
['country', 'type', 'type' => 'string'],
['country', 'length', 'max' => 50],
];
}
}
当您使用此模型时,您只需要通过$model->validate()
验证此模型,如果失败 - 使用$model->getErrors()
显示错误。 此外,您可以指定要使用的规则方案。 例如: $model->senario = 'search';
将使用验证规则search
和属性name
应该是数组。 但是当场景insert
名称应该是长度不超过100的字符串。
在我的示例字段中:名称,国家/地区 - 插入所需( ['name, country', 'on' => 'insert']
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.