2017-05-16 47 views
2

我有三个实体,如下列: 1 Customer.php如何获取doctrine2关系有条件

<?php 

//... 

/** 
* Customer 
* 
* @ORM\Table(name="customers") 
* @ORM\Entity(repositoryClass="CompanyBundle\Repository\CustomerRepository") 
* @ORM\HasLifecycleCallbacks 
*/ 
class Customer 
{ 
    /** 
    * @ORM\OneToMany(targetEntity="CustomerAddress", mappedBy="customer") 
    */ 
    private $customerAddresses; 

    // ... 
} 

?> 

2. CustomerAddress.php

<?php 

//... 

/** 
* CustomerAddress 
* 
* @ORM\Table(name="customer_address") 
* @ORM\Entity(repositoryClass="CompanyBundle\Repository\CustomerAddressRepository") 
*/ 
class CustomerAddress 
{ 
    /** 
    * @ORM\ManyToOne(targetEntity="Customer", inversedBy="customerAddresses") 
    * @ORM\JoinColumn(name="customer_id", referencedColumnName="id", onDelete="CASCADE") 
    */ 
    private $customer; 

    /** 
    * @ORM\ManyToOne(targetEntity="CustomerAddressType", inversedBy="customerAddresses") 
    * @ORM\JoinColumn(name="customer_address_type_id", referencedColumnName="id", onDelete="CASCADE") 
    */ 
    private $customerAddressType; 

    //... 

} 

3 CustomerAddressType。 php

<?php 

//... 

/** 
* CustomerAddressType 
* 
* @ORM\Table(name="customer_address_type") 
* @ORM\Entity(repositoryClass="CompanyBundle\Repository\CustomerAddressTypeRepository") 
*/ 
class CustomerAddressType 
{ 
    /** 
    * @ORM\OneToMany(targetEntity="CustomerAddress", mappedBy="customerAddressType") 
    */ 
    private $customerAddresses; 

    //... 
} 

下面是从行表customer_address_type

Here are the rows from table

我想类型是“BA”或“SA”的所有客户的地址。所以我想删除除这两个之外的所有其他类型。基本上我想在Laravel中做类似于查询范围的事情。

foreach ($customers as $customer) { 
     // Here I want to filter customer addresses 
     // Currently its giving me all 
     $customer_address = $customer->getCustomerAddresses(); 
    } 

有没有可能这样做,而不使用自定义查询?

+3

为什么要避免自定义查询?毕竟这就是数据库系统的原因! –

+0

如果在你的'Repository'中没有自定义查询,你就无法做到这一点。 – tftd

+0

@PhilippFlenker,因为我想要重用那部分代码,并且它会帮助序列化 –

回答

0

你可以得到一个包含所有地址的ArrayCollection,然后使用过滤器方法来获取你想要的。您可以在Customer实体内部执行此操作,以便您可以重复使用它进行序列化。

你要通过封闭的过滤方法,然后遍历集合评估时要包括在结果还是假的如果不是项目应该renturn真正关闭。