2016-08-03 53 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()'。 –

相关问题