2017-05-19 6 views
1

エンティティ内のいくつのフィールドがヌルでないかをカウントしようとしています。具体的には、プロパティがArrayCollectionの場合、コレクションが空でないかどうかを識別します。ここでエンティティのプロパティを反復し、ヌル値でない値を返します。

どのエンティティプロパティをループすると、空のヌルかどうかではない性質を数える私は、すべてのユーザーオブジェクトのプロパティに

$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 

答えて

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は、エンティティであるどのように多くの空の性質を示します。

注意:このコードは本番では使用しないでください!

関連する問題