我在正确设置教义映射时遇到问题。

我有一个CashRegister实体,该实体具有容器位置和返回容器位置。两个位置都来自同一类型(BinLocation实体)。

CashRegisterCashRegister->getBinLocations()CashRegister->getReturnBinLocations()传出的正常工作,但是如何实现BinLocation->getCashRegisters()返回所有被引用的CashRegister实体(binLocation + returnBinLocation)?

/**
 * CashRegister
 *
 * @ORM\Table(name="cash_registers")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class CashRegister
{

    ...

    /**
     * @var BinLocation
     *
     * @ORM\ManyToOne(targetEntity="BinLocation", inversedBy="cashRegisters")
     * @ORM\JoinColumn(name="bin_location_id", referencedColumnName="id")
     */
    private $binLocation;

    /**
     * @var BinLocation
     *
     * @ORM\ManyToOne(targetEntity="BinLocation", inversedBy="cashRegisters")
     * @ORM\JoinColumn(name="return_bin_location_id", referencedColumnName="id")
     */
    private $returnBinLocation;


    /**
     * @return BinLocation
     */
    public function getBinLocation()
    {
        return $this->binLocation;
    }

    /**
     * @return BinLocation
     */
    public function getReturnBinLocation()
    {
        return $this->returnBinLocation;
    }

    ...

}

/**
 * BinLocation
 *
 * @ORM\Table(name="bin_locations")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class BinLocation
{

    ...

    /**
     * @var CashRegister[]
     *
     * @ORM\OneToMany(targetEntity="CashRegister", mappedBy="binLocation") <= Here is the problem, in this case mappedBy need to be an array [binLocation, returnBinLocation]
     */
    private $cashRegisters;


    /**
     * @return CashRegister[]
     */
    public function getCashRegisters()
    {
        return $this->cashRegisters;
    }

    ...

}

最佳答案

简单的答案是您不能。 mappedBy仅接受一个参数。

但是,实现所需目标的解决方案却很简单。在BinLocation中创建第二个属性,称为:cashRegisters2,如下所示:

/**
 * @var CashRegister[]
 *
 * @ORM\OneToMany(targetEntity="CashRegister", mappedBy="binLocation")
 */
private $cashRegisters;

/**
 * @var CashRegister[]
 *
 * @ORM\OneToMany(targetEntity="CashRegister", mappedBy="binLocation")
 */
private $cashRegisters2;

然后将Collections合并到getCashRegisters方法中。
/**
 * @return CashRegister[]
 */
public function getCashRegisters()
{
    return new ArrayCollection(
                      array_merge($cashRegisters->toArray(), $cashRegisters2->toArray())
    );
}

还要相应地更改CashRegister映射:
/**
 * @var BinLocation
 *
 * @ORM\ManyToOne(targetEntity="BinLocation", inversedBy="cashRegisters")
 * @ORM\JoinColumn(name="bin_location_id", referencedColumnName="id")
 */
private $binLocation;

/**
 * @var BinLocation
 *
 * @ORM\ManyToOne(targetEntity="BinLocation", inversedBy="cashRegisters2")
 * @ORM\JoinColumn(name="return_bin_location_id", referencedColumnName="id")
 */
private $returnBinLocation;

注意:我没有测试代码。本示例仅用于服务器指南。

注2: ArrayCollection合并是从此处启发的:https://stackoverflow.com/a/16871539/2853903

关于php - 教义2的多重映射,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31284911/

10-12 15:52