如何有条件地获取doctrine2关系

时间:2017-05-16 08:41:06

标签: php symfony doctrine-orm

我有以下三个实体: 的 1。 Customer.php

<?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

我想获得所有类型的客户地址&#39; BA&#39;或者&#39; SA&#34;。所以除了这两个外,我想删除所有其他类型。基本上我想在Laravel中做类似于查询范围的事情。

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

如果不使用自定义查询,是否可以这样做?

1 个答案:

答案 0 :(得分:0)

您可以获取包含所有地址的ArrayCollection,然后使用filter方法只获取您想要的地址。您可以在Customer实体中执行此操作,以便可以重复使用它进行序列化。

你必须将一个闭包传递给filter方法,然后迭代遍历集合,评估当你想在结果中包含项时应该为true的闭包,否则为false。