Checking if a relationship exists I'm using a many-to-many relationship between users and roles with propel:

&lt;table name="user"&gt;
    &lt;column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" /&gt;
    &lt;column name="username" required="true" type="varchar" primaryKey="true" size="50" /&gt;
&lt;/table&gt;

&lt;table name="role"&gt;
    &lt;column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" /&gt;
    &lt;column name="role" required="true" type="varchar" size="20" primaryString="true" /&gt;
    &lt;column name="name" required="true" type="varchar" size="50" /&gt;

    &lt;unique&gt;
        &lt;unique-column name="role" /&gt;
        &lt;unique-column name="name" /&gt;
    &lt;/unique&gt;
&lt;/table&gt;

&lt;table name="user_role" isCrossRef="true"&gt;
    &lt;column name="user_id" type="integer" primaryKey="true"/&gt;
    &lt;column name="role_id" type="integer" primaryKey="true"/&gt;
    &lt;foreign-key foreignTable="user"&gt;
        &lt;reference local="user_id" foreign="id"/&gt;
    &lt;/foreign-key&gt;
    &lt;foreign-key foreignTable="role"&gt;
        &lt;reference local="role_id" foreign="id"/&gt;
    &lt;/foreign-key&gt;
&lt;/table&gt;


This is how I check if a user has a role:

class User extends BaseUser
{       
    public function hasRole($checkRole)
    {
        foreach ($this-&gt;getRoles() as $role)
        {
            if ($role-&gt;getRole() == $checkRole)
            {
                return true;
            }
        }

        return false;
    }
}


This works, but I think it could be optimized. Any ideas?
You don't have to loop throught the collection since you can directly query the database or your object if it is already loaded:

class User extends BaseUser
{       
    public function hasRole($checkRole)
    {
        $userWithRole = UserQuery::create()
            -&gt;filterByRole($checkRole)
            -&gt;findOne();

        return !is_null($userWithRole);
    }
}


You can either check that $userWithRole is not null like I did or if it is an instance of User.

If your objects are already hydrated you can avoid the query by querying the Roles collection:

class User extends BaseUser
{       
    public function hasRole($checkRole)
    {
        return $this-&gt;getRoles()-&gt;contains($checkRole);
    }
}