迭代实体属性并计算非空值

时间:2017-05-19 08:29:35

标签: php symfony doctrine-orm doctrine

我试图计算实体中有多少字段不为空。具体来说,如果属性是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

1 个答案:

答案 0 :(得分:0)

您需要定义一个实体对象以将其传递给循环。例如$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将显示实体中有多少空属性。

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