【问题标题】:Iterate entity properties and count not null values迭代实体属性并计算非空值
【发布时间】:2017-05-19 19:39:38
【问题描述】:

我正在尝试计算实体中有多少字段不为空。具体来说,如果属性是ArrayCollection,判断collection是否不为空。

我在这里获取所有用户对象属性

   $properties = $em->getClassMetadata('AppBundle:User')->getFieldNames();
   $output = array_merge(
        $properties,
        $em->getClassMetadata('AppBundle:User')->getAssociationNames()
    );

   foreach($output as $property){
          ????
   }

关于如何遍历实体属性并计算非空或非空属性的问题。

var_dump($output) 输出:

array (size=47)
  0 => string 'username' (length=8)
  1 => string 'usernameCanonical' (length=17)
  2 => string 'email' (length=5)
  3 => string 'emailCanonical' (length=14)
  ... 
  45 => string 'expertise' (length=13) // ManyToOne association
  46 => string 'reports' (length=7) // OneToMany association. type ArrayCollection

【问题讨论】:

    标签: php symfony doctrine-orm doctrine


    【解决方案1】:

    您需要定义一个实体对象以将其传递给循环。例如$entity = $em->getRepository(User::class)->find(1);

    您的示例代码可能看起来像这样

    $properties = $em->getClassMetadata(User::class)->getFieldNames();
    $output = array_merge(
        $properties,
        $em->getClassMetadata(User::class)->getAssociationNames()
    );
    
    $entity = $em->getRepository(User::class)->find(1);
    $reflector = new \ReflectionObject($entity);
    $count = 0;
    
    foreach ($output as $property) {
        $method = $reflector->getMethod('get'.ucfirst($property));
        $method->setAccessible(true);
        $result = $method->invoke($entity);
        if ($result instanceof PersistentCollection) {
            $collectionReflector = new \ReflectionObject($result);
            $method = $collectionReflector->getMethod('count');
            $method->setAccessible(true);
            $result = $method->invoke($result);
        }
        $result == null ?: $count++;
    }
    

    变量$count 将显示实体中有多少个空属性。

    注意: 此代码不应在生产环境中使用!

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多