Доктрина 2 множественное отображение?
У меня проблема с правильной настройкой отображения Доктрины.
У меня есть объект CashRegister
, у которого есть местоположение ячейки и местоположение возвращаемой ячейки. Оба местоположения относятся к одному и тому же типу (BinLocation
Сущности).
Исходящий из CashRegister
, CashRegister->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;
}
...
}
2 answers
Простой ответ заключается в том, что вы не можете. mappedBy
принимает только один аргумент.
Решение для достижения того, чего вы хотите, однако, простое. Создайте второе свойство в BinLocation
с именем: cashRegisters2
следующим образом:
/**
* @var CashRegister[]
*
* @ORM\OneToMany(targetEntity="CashRegister", mappedBy="binLocation")
*/
private $cashRegisters;
/**
* @var CashRegister[]
*
* @ORM\OneToMany(targetEntity="CashRegister", mappedBy="binLocation")
*/
private $cashRegisters2;
Затем объедините коллекции в своем методе 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: Коллекция массивов слияние было вдохновлено отсюда: https://stackoverflow.com/a/16871539/2853903
Я также искал решения и сделал исправление для доктрины, чтобы вы могли использовать атрибуты custom_attributes, связанные с различными типами сущностей.
Доктрина 2.6: https://github.com/danielbeeke/doctrine2/commit/2d8530176b872cb490c5c88b8c8e17d8d0091388 Доктрина 2.7: https://github.com/danielbeeke/doctrine2/commit/5bde696848ea9fe7035fadc4d46baa4c0d51f3a2
/**
* @Entity
* @Table(name="product")
* @HasLifecycleCallbacks
**/
class Product {
/**
* One Product has Many Attributes.
*
* @OneToMany(
* targetEntity="CustomAttribute",
* mappedBy="EntityId",
* mappedByType={
* "field": "EntityType",
* "value": "product"
* }
* )
*
* @var $CustomAttributes ArrayCollection
*/
protected $CustomAttributes;
}
/**
* @Entity
* @Table(name="custom_attribute")
* @HasLifecycleCallbacks
**/
class CustomAttribute_entity {
/** @Id @Column(type="integer") @GeneratedValue */
protected $Id;
/**
* Many Attributes have One Entity of the EntityType provided.
* @ManyToOne(targetEntity="Product", inversedBy="CustomAttributes")
* @JoinColumn(name="EntityId", referencedColumnName="Id")
*/
protected $EntityId;
/** @Column(type="string") */
protected $EntityType;
/** @Column(type="string") */
protected $Type;
/** @Column(type="string") */
protected $Value;
}