是否可以覆盖@ManyToOne(targetEntity)
?
我看过this Doctrine documentation page,但没有提到如何覆盖targetEntity
。
这是我的代码:
namespace AppBundle\Model\Order\Entity;
use AppBundle\Model\Base\Entity\Identifier;
use AppBundle\Model\Base\Entity\Product;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\AttributeOverrides;
use Doctrine\ORM\Mapping\AttributeOverride;
/**
* Class OrderItem
*
*
* @ORM\Entity
* @ORM\Table(name="sylius_order_item")
* @ORM\AssociationOverrides({
* @ORM\AssociationOverride(
* name="variant",
* joinColumns=@ORM\JoinColumn(
* name="variant", referencedColumnName="id", nullable=true
* )
* )
* })
*/
class OrderItem extends \Sylius\Component\Core\Model\OrderItem
{
/**
* @var
* @ORM\ManyToOne(targetEntity="AppBundle\Model\Base\Entity\Product")
*/
protected $product;
/**
* @return mixed
*/
public function getProduct()
{
return $this->product;
}
/**
* @param mixed $product
*/
public function setProduct($product)
{
$this->product = $product;
}
}
我能够覆盖“variant”列的定义并将此列设置为null,但我无法弄清楚如何更改targetEntity
。
答案 0 :(得分:2)
如文档中所述,您无法更改关联的类型: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#association-override
但是,您可以将targetEntity定义为接口(这似乎是默认的sylius conf),
namespace AppBundle\Entity;
use Sylius\Component\Core\Model\ProductInterface as BaseProductInterface;
interface ProductInterface extends BaseProductInterface {}
扩展接口文件中的原始文件
doctrine:
orm:
resolve_target_entities:
AppBundle\Entity\ProductInterface: AppBundle\Entity\Product
并在配置中添加映射
select id
from customer
where firstname in (select firstname
from customer
group by firstname
having count(*)>1);
这里描述:http://symfony.com/doc/current/doctrine/resolve_target_entity.html
希望有所帮助
答案 1 :(得分:0)
使用注释时,我没有找到一种方法来覆盖关联的targetEntity
值,但是使用PHP映射(Symfony中的php
或staticphp
)是可行的。
https://www.doctrine-project.org/projects/doctrine-orm/en/current/reference/php-mapping.html
我们可以创建一个函数:
function updateAssociationTargetEntity(ClassMetadata $metadata, $association, $targetEntity)
{
if (!isset($metadata->associationMappings[$association])) {
throw new \LogicException("Association $association not defined on $metadata->name");
}
$metadata->associationMappings[$association]['targetEntity'] = $targetEntity;
}
并像这样使用它:
updateAssociationTargetEntity($metadata, 'product', AppBundle\Model\Base\Entity\Product::class);
这样,当Doctrine加载类AppBundle\Model\Order\Entity\OrderItem
的元数据时,它首先加载父级(\Sylius\Component\Core\Model\OrderItem
)元数据,然后为子类加载PHP映射,在此我们重写了关联加载父类元数据时设置的映射。