Search code examples
phpcakephpentity-relationshipforeign-key-relationshipdatabase-relations

Cakephp Polymorphic relationship


I am developing an user system, this system has 3 types of users:

  1. Company employers
  2. Clients
  3. Providers

All users has many properties so i distribuite in users tables with login information and profiles tables with users details

My schema is something like this:

users (with username, email, password, profile_id)

user_profiles (for company employers information)

client_profiles (for client information)

provider_profiles (for providers details)

Im working with CakePHP 2.x and need to declare the relationship between profile_id field of my users table and my three types of profiles users tables Researching on internet i found this is something called polymorphic relationship, Laravel has something like this: http://laravel.com/docs/eloquent#polymorphic-relations but obviously i cant change the framework

I hope somebody could show how to declare this relation in CakePHP if it is possible

If you need more information about the problem please ask me Thanks in advance


Solution

  • The straight forward solution would be: add all three xyz_profile_id fields to the users table and define in the model-validate rules, that all three fields can be empty. You have to check that the right table is connected to your user in the controller. But in my opinion this would be more simple than fiddling around in each and every controller action, which table is actually associated with this column.

    if the three tables have nothing in common, they should not share the same id-reference column. When they all have the same columns, why not merging them to the users-table?