Reputation: 182
I am not sure what is the correct title. Here is my problem:
There are several models such as:
Company
Person (not same as the Users)
User
etc.
Some of them needs to have one or more files attached to them.
So I have created an UploadedFile model. How to link this to any of the above models? Sometimes the UploadedFile belongs to a Company. Sometimes the UploadedFile belongs to Person
If an UploadedFile belongs to a Company, then it doesn't belong to others like Person.
All UploadedFile belongs to User (because they upload them and I need to track who uploaded it)
Does HABTM works here? Any other better ways?
Thank you very much for help.
Best regards,
Tony.
Upvotes: 0
Views: 420
Reputation: 6448
Make the UploadedFile belog to all three (User, Company and Person):
var $belongsTo = array(
'User' => array('className' => 'User','foreignKey' => 'user_id'),
'Company' => array('className' => 'Company','foreignKey' => 'company_id'),
'Person' => array('className' => 'Person','foreignKey' => 'person_id'));
Since it always belong to a User, the user_id will always have a value.
Then you will check whether the company_id is set or the person_id is set and determine to which of them the file belongs. I have an application that works just like this. It is a bit painstaking, but I could not find any other solution
Another good idea will be to try and combine Person and Company in a single table, and just have a flag to distinguish between the two.
Upvotes: 1