2016-08-03 56 views
0

我有一個父對象是什麼帳戶。這個賬戶對象與它的子對象有一個一對多的關係,一個mailList是什麼。如何從Symfony2中的一對多關係中獲取父對象的子對象

Parent: 

    class CusAccount 
    { 

     public function __construct() 
     { 
      $this->mailList = new ArrayCollection(); 
     } 

     /** 
     * @ORM\OneToMany(targetEntity="MailList", mappedBy="account") 
     */ 
     private $mailList; 

     /** 
     * Get mailList 
     * 
     * @return \Doctrine\Common\Collections\Collection 
     */ 
     public function getMailList() 
     { 
       return $this->mailList; 
     } 

    } 

Child: 

class MailList 
{ 

    /** 
    * @ORM\ManyToOne(targetEntity="CusAccount") 
    * @ORM\JoinColumn(name="account_id", referencedColumnName="id") 
    */ 
    private $account; 

    /** 
    * @var string 
    * 
    * @ORM\Column(name="email", type="string", length=50) 
    * 
    */ 
    private $email; 

} 

將多個孩子添加到父母工作正常。我再次檢查數據庫。還得到第一個孩子回來的作品:

$child = $account->getMailinglist()->first(); 

只有現在我想通過它的電子郵件地址找到一個孩子。我找不到這個正確的代碼?

回答

0

可以過濾集合找到你需要的東西:

$allChildrenWithSearchedEmail = $account->getMailinglist()->filter(function($child) { 
    return ($child->getEmail() == "[email protected]"); 
}); 
+0

謝謝你,是不是也有可能只得到下令電子郵件完整的子列表? – Tom

+0

在這種情況下,您可以使用'getMailinglist() - > getValues()'作爲數組獲取所有條目,並在該數組上使用'usort()'。 –

相關問題