Doctrine2 - 如何限制@OneToMany映射大小?

And*_*rea 0 entity-relationship one-to-many symfony doctrine-orm

我想知道是否有任何方法可以@OneToMany在Doctrine2 中设置关系大小的约束.

假设我有2个课程:UserToy:

class User{
    ...
    /**
     * @OneToMany(targetEntity="Toy", mappedBy="user")
     */
    public $toys;
    ...
}
class Toy{
    ...
    /**
     * @ManyToOne(targetEntity="User", inversedBy="toys")
     */
    public $user;
    ...
}
Run Code Online (Sandbox Code Playgroud)

我想强迫每个用户最多拥有3个玩具.你知道是否有办法通过使用任何Doctrine2注释来实现这一点?

如果通过注释无法实现,你会怎么做?

谢谢!

Pat*_*and 6

class User {
 [..]
 public function addToy (Toy $toy)
 {
   if(count($this->toys) >= 3 && !$this->toys->contains($toy)) {
     throw new User\ToyLimitExceededException(
       'At most 3 toys are allowed per user, tried to add another!'
     );
   }
   $this->toys->add($toy);
   $toy->setUser($this);
   return $this;
 }
 [..]
}
Run Code Online (Sandbox Code Playgroud)