先决条件:
- PHP 7.1.8
- Symfony 3.3.9
- Doctrine 2.6.x-dev
我想知道是否可以覆盖从 trait 中获取的属性关联映射的 inversedBy
属性。
我使用作为具体用户实体占位符的接口:
ReusableBundle\ModelEntrantInterface.php
interface EntrantInterface
{
public function getEmail();
public function getFirstName();
public function getLastName();
}
- 以下结构可以很好地工作(需要创建实现
EntrantInterface
的User
实体以及所有其他从这些抽象类派生的实体在AppBundle
中):
ReusableBundle\Entity\Entry.php
/**
* @ORM\MappedSuperclass
*/
abstract class Entry
{
/**
* @var EntrantInterface
*
* @ORM\ManyToOne(targetEntity="ReusableBundle\Model\EntrantInterface", inversedBy="entries")
* @ORM\JoinColumn(name="user_id")
*/
protected $user;
// getters/setters...
}
ReusableBundle\Entity\Timestamp.php
/**
* @ORM\MappedSuperclass
*/
abstract class Timestamp
{
/**
* @var EntrantInterface
*
* @ORM\ManyToOne(targetEntity="ReusableBundle\Model\EntrantInterface", inversedBy="timestamps")
* @ORM\JoinColumn(name="user_id")
*/
protected $user;
// getters/setters...
}
还有一些结构类似的实体,它们使用EntranInterface
。
- 这就是我想要实现的-使
UserAwareTrait
可以在多个实体中重复使用:
ReusableBundle\Entity\Traits\UserAwareTrait.php
trait UserAwareTrait
{
/**
* @var EntrantInterface
*
* @ORM\ManyToOne(targetEntity="ReusableBundle\Model\EntrantInterface")
* @ORM\JoinColumn(name="user_id")
*/
protected $user;
// getter/setter...
}
在Doctrine 2.6中,如果我想使用超类并想要覆盖其属性,我会这样做:
/**
* @ORM\MappedSuperclass
* @ORM\AssociationOverrides({
* @ORM\AssociationOverride({name="property", inversedBy="entities"})
* })
*/
abstract class Entity extends SuperEntity
{
// code...
}
但如果我想让该实体使用 UserAwareTrait
并重写属性的关联映射...
/**
* @ORM\MappedSuperclass
* @ORM\AssociationOverrides({
* @ORM\AssociationOverride({name="user", inversedBy="entries"})
* })
*/
abstract class Entry
{
use UserAwareTrait;
// code...
}
当我运行php bin/console doctrine:schema:validate
时,我在控制台中看到了以下错误:
[Doctrine\ORM\Mapping\MappingException]
Invalid field override named 'user' for class 'ReusableBundle\Entity\Entry'.
是否有解决方法可以实现所需的结果?
使用trait来存储共享属性
覆盖使用该trait的类中的关联映射或(可能)属性映射
abstract class Entry
上的@ORM\MappedSuperclass
行了吗?更重要的是:您尝试覆盖关系而没有指定它(在这种情况下为ManyToOne)。请尝试:@ORM\AssociationOverrides({ @ORM\AssociationOverride(name="user", manyToMany=@ORM\ManyToOne(targetEntity="ReusableBundle\Model\EntrantInterface", inversedBy="entities")) })
。 - goulashsoupinversedBy="entries"
,与原始代码相同,在你的倒数第二个代码块中,它是inversedBy="entities"
... - goulashsoup