Reputation: 3717
I was wondering if there exists any way to set a constraint on the size of a @OneToMany
relation in Doctrine2.
Let's say I have 2 classes: User
and Toy
:
class User{
...
/**
* @OneToMany(targetEntity="Toy", mappedBy="user")
*/
public $toys;
...
}
class Toy{
...
/**
* @ManyToOne(targetEntity="User", inversedBy="toys")
*/
public $user;
...
}
I would like to force each user to have at most 3 toys. Do you know if there is a way to achieve this by using any Doctrine2 annotation?
If it is not possible through annotations, how would you do this?
Thanks!
Upvotes: 0
Views: 1845
Reputation: 45721
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;
}
[..]
}
Upvotes: 6