Php 迭代实体属性并计数非空值

Php 迭代实体属性并计数非空值,php,symfony,doctrine-orm,doctrine,Php,Symfony,Doctrine Orm,Doctrine,我试图计算实体中有多少字段不是空的。特别是,如果属性为ArrayCollection,请确定集合是否为空 这里我得到了所有的用户对象属性 $properties = $em->getClassMetadata('AppBundle:User')->getFieldNames(); $output = array_merge( $properties, $em->getClassMetadata('AppBundle:User')-&g

我试图计算实体中有多少字段不是空的。特别是,如果属性为ArrayCollection,请确定集合是否为空

这里我得到了所有的用户对象属性

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

   foreach($output as $property){
          ????
   }
询问如何循环实体属性并计算非空或非空属性

var\u 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

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


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

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

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