1
\$\begingroup\$

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

<table name="user">
    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
    <column name="username" required="true" type="varchar" primaryKey="true" size="50" />
</table>

<table name="role">
    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
    <column name="role" required="true" type="varchar" size="20" primaryString="true" />
    <column name="name" required="true" type="varchar" size="50" />

    <unique>
        <unique-column name="role" />
        <unique-column name="name" />
    </unique>
</table>

<table name="user_role" isCrossRef="true">
    <column name="user_id" type="integer" primaryKey="true"/>
    <column name="role_id" type="integer" primaryKey="true"/>
    <foreign-key foreignTable="user">
        <reference local="user_id" foreign="id"/>
    </foreign-key>
    <foreign-key foreignTable="role">
        <reference local="role_id" foreign="id"/>
    </foreign-key>
</table>

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

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

        return false;
    }
}

This works, but I think it could be optimized. Any ideas?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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()
            ->filterByRole($checkRole)
            ->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->getRoles()->contains($checkRole);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Check the API of Propel\Runtime\Collection\Collection class and its derivatives. There are many more useful functions. \$\endgroup\$
    – ragol
    Oct 7, 2014 at 15:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.