Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Techniques to check if relationship exists in Doctrine2

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;
    } 
}
like image 282
calumbrodie Avatar asked Jun 03 '11 08:06

calumbrodie


2 Answers

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();
} 
like image 72
calumbrodie Avatar answered Oct 29 '22 16:10

calumbrodie


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.

like image 23
Crozin Avatar answered Oct 29 '22 16:10

Crozin