p9807
p9807

Reputation: 615

New to CakePHP/Model use

I have a table/model of users, and a certain subset of those users have an entry in a "roles" table.

What is the standard way to create a model that has access to all the users who have one or more entries/rows in the roles table?

Thanks!

Upvotes: 0

Views: 172

Answers (1)

Charles Sprayberry
Charles Sprayberry

Reputation: 7853

Welcome to Cake!

One of the coolest and most powerful aspects of Cake is their very capable ORM. Once you figure out Cake's associations and the way they work with databases it's hard to go back to something else. But, there's a couple things we need to make sure we do with our actual physical database schema before we can do this.

So, let's work with some "sample" data.

users
 -------------------------------------------------------
|  id (PK)  |  role_id (FK)  |  username  |  password   |
 -------------------------------------------------------
|     1     |         1      |  cspray     |  ad64675   |
 -------------------------------------------------------

...and so on and so on.

roles
 --------------------------------------------
|  id (PK)  |              name              |
 --------------------------------------------
|  1        |  Benevolent Dictator for Life  |
 --------------------------------------------

...and so on and so on.

Note the name of the tables, users and roles, and the field names, specifically id and role_id. Those are important. id is normally an auto increment, int field in your database. There's other ways to store your id key but let's not pile too much on at once.

Now, all this and we haven't answered your question yet! Don't worry we're about to get to that. But, first double check your database schema and make sure those table names and columns are named according to Cake convention. Don't worry I'll wait...

...

Ok! Now open up your favorite text editor and navigate to install_dir/app/models/ (where install_dir is the name of the folder you have the framework installed in). Once there create a new file and name it user.php. Inside this file we're gonna use some code that looks like this...

class User extends AppModel {

    public $belongsTo = array('Role');

}

And, well, there you have it! You're now free to query the roles table from within your User class by calling methods through Cake's "association chain", $this->User->Role->find(). You can, and probably should, create a Role model just like you created User, sans the $belongsTo. Inside it you can define your own methods to interact with the roles table and give the information you need to User.

I don't want to go too much into how Cake's ORM works though, mostly because if you read through the Cake Cookbook and the Cake API you will find a wealth of knowledge ready to be plucked.

Enjoy your ventures into Cake!


So, your model associations are all setup and you're ready to go. But, where do you go? Well, you'll want to check out Cake's Model behaviors, particularly one of the most important core behaviors, Containable. This will allow you to do exactly what you want to do.

Let's just take a look at some code, I'm going to assume that you're already familiar with the Model::find() method. If not I'd go check that out real quick so you don't get too confused. It's fairly straight-forward though.

class User extends AppModel {

    // provides $this->User->Role
    public $belongsTo = array('Role');

    // gives access to various behaviors
    public $actsAs = array('Containable');

    // custom function
    public function get_users_with_roles() {

        return $this->User->find(
            'contain' => array(
                'Role' => array(     // tells ORM to query `roles` table
                    'Hour',         // <-- tells ORM to query `hours` table
                    'conditions' => array(
                       'Role.id' => '<> NULL'
                    )
                )
            ),
            'fields' => array(
                'User.username'
            )
        );

    }

}

This should return all user's usernames (and possibly their id and role_id as well) that have an entry in the roles table. Note the addition of the new property and the way the "query" is laid out in Cake's ORM. One thing I could suggest getting comfortable with is multi-dimensional associative arrays, Cake uses a lot of them.

Upvotes: 3

Related Questions