I'm creating a web application that will use multiple types of users (e.g. Admin, Managers, Users). Each user will require different pieces of information stored about them, some will be the same across each user type (i.e. username, password, email) and others will be different.

I'm wondering the best way to have the database, whilst using the ACL & Auth components in CakePHP. I see 2 possible solutions:

  1. Have three tables, one for each user type.
  2. Have five tables. A user table, a groups table, and then three tables containing the extra fields for each user type.

The problem I see with 1 is, I'm not sure how easy it is for CakePHP to use different models for permissions, instead of using a groups table. So, I think the second solution will be the easiest to set up, and maybe maintain, but is there too much overhead with the 3 extra tables? Or is there a better solution that I haven't thought about?

Accepted Answer

You could create a table that belongsTo User called user_data with the columns:

  • id
  • user_id
  • key
  • value

User HasMany UserData and UserData BelongsTo User

See http://book.cakephp.org/view/1043/hasMany and http://book.cakephp.org/view/1042/belongsTo for reference on how to setup relational data.

$data = array(
    'UserData' => array(
        'user_id' => 2,
        'key' => 'birthday',
        'value' => 'Oct 6th',
        'type' => 'admin'
    )
);

Then, in controller, you can fetch the custom data with Containable behavior:

$this->set('user', $this->User->find('first', array('conditions' => array('User.id' => 2), 'contain' => array('UserData'))));

In the view (Probably best to make this a helper function)

$birthday = Set::extract('/User/UserData[key=birthday]', $user);
echo $birthday[0]['value'];
Written by William Golden
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki