如何检查模型的任何字段是否为空或为空?

How to check if any of the fields of a model are null or empty?

我有一个模型,$userModel。我想检查此模型的 any 字段是否为空或 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)) { .. }

empty() DOCS

  • ""(空字符串)
  • 0(整数 0)
  • 0.0(0 作为浮点数)
  • "0"(0 作为字符串)
  • 错误
  • array()(空数组)
  • $变量; (声明的变量,但没有值)

更新

$modelData = array($userModel->name, $userModel->address, $userModel->email);
if(!in_array('', $modelData) && !in_array(null, $modelData)) { .. }

in_array()

或者您可以使用 array_intersect -

if(empty(array_intersect(array('', null), $modelData))) { .. }

array_intersect()

PHP 允许您 iterate over an object's properties. The check for each property could be simplified using empty():

$allHaveValues = TRUE;
foreach ($userModel as $key => $value) {
    if (empty($value)) {
       $allHaveValues = FALSE;
       break;
    }
}

if ($allHaveValues) {
    // Do something...
}

我认为你不需要这样做。
您需要的一切 - 它只是指定您的验证规则。
例如:

<?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 name 应该是长度不超过 100 的字符串时。

在我的示例字段中:姓名、国家/地区 - 需要插入 (['name, country', 'on' => 'insert'])。