0

我想知道是否有任何方法可以对@OneToManyDoctrine2 中的关系大小设置约束。

假设我有 2 个课程:UserToy

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

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

如果通过注释无法实现,您将如何做到这一点?

谢谢!

4

1 回答 1

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;
 }
 [..]
}
于 2012-04-04T09:48:20.263 回答