Kyle O'Brien
Kyle O'Brien

Reputation: 952

Cakephp - Multiple Models for one Table

I have a User model that is used to store data on users of a dental examination system.

Typically, three types of users will exist: Admininistrator, Location Manager and Examiner.

It seems to have become necessary to treat these three roles as seperate models in my application (imagine how I'd have a different view for each role with different options etc... It's a nightmare).

How would I go about setting up the relationships in each Model.

My first thought is:

//Administrator Model
class Administrator extends User {
    $name = 'Administrator';
    $table = 'User';
    $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'conditions' => array('User.role' => 'administrator'), 
        )
    );
}

And then the User model will reference this one using a hasMany? In terms of CakePHP convention, how would one actually model this accurately?

Also, would this model extend the User model or the AppModel?

Upvotes: 2

Views: 1902

Answers (1)

Jacek Barecki
Jacek Barecki

Reputation: 429

Of course you can create different models using the same table name. To do so, link each model with specific table with $useTable property (not $table):

class Administrator extends AppModel {
    public $useTable = 'User';
}

But I don't know any CakePHP model property which will allow you to filter data returned when fetching results... You can only write your own conditions when linking model with another one, for example:

class SomeOtherModel extends AppModel {
    public $hasMany = array(
        'Administrator' => array(
            'className' => 'Administrator',
            'conditions' => array('Administrator.role' => 'administrator')
        )
    );
}

Which is not a good solution, because it will work only when executing queries for SomeOtherModel model.

You can also try applying an afterFind() callback to your Administrator / Examiner / ... models which will delete users of another role than needed, but of course it is not an efficient solution.

Another solution is just creating different database views which will contain only users of selected role (more on views - here). Then you can point each view to your CakePHP model, just as it was a normal database table. But this solution is also not perfect. If you will have to add a new user role or change your table schema in the future, you will also have to modify your database views.

Upvotes: 2

Related Questions