I can't seem to find any mention in the Doctrine documentation on how to check if an entity has an existing relationship to another entity:
http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html
In Doctrine 1.x there was a method called exists
that could be called on an entity to check this:
http://www.doctrine-project.org/documentation/manual/1_2/en/working-with-models#dealing-with-relations:clearing-related-records
In Doctrine 2.0 this is what I've tended to do. What techniques are other people using?
<?php
class Group {
private $id;
protected $name;
protected $users;
public function __construct()
{
$this->colorgroups = new ArrayCollection();
}
public function hasUsers() {
return count($this->users) > 0;
}
}
Well - I actually stumbled on the correct answer today while looking though the ArrayCollection class. You should use the 'isEmpty' method.
From the code (the comments are theirs, not mine)
/**
* Checks whether the collection is empty.
*
* Note: This is preferrable over count() == 0.
*
* @return boolean TRUE if the collection is empty, FALSE otherwise.
*/
public function isEmpty()
{
return ! $this->_elements;
}
So from my example
public function hasUsers() {
return !$this->users->isEmpty();
}
Doctrine2 uses different architecture than Doctrine1.2. If you want to check whether a group has a certain user associated with it you should write a method hasUser(User $user)
that will determine it:
public function hasUser(User $user) {
foreach ($this->users as $u) {
if ($u->equals($user)) {
return true;
}
}
return false;
}
If you want to check whether a relationship is persisted in database you will have to execute a the following DQL query:
SELECT 1 FROM MyProject\Entity\Group g WHERE :user MEMBER OF g.users;
Where :user
is User
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With