Shlomi Atia Shlomi Atia - 2 months ago 16
MySQL Question

Laravel 5.3 files table related to multiple tables

I have one table named "files" which I would like to contain all my users files.
The files can be uploaded from different views and should be related to different tables: questions table, answers table, comments table, messages table etc... but still, all of them will be related also to users table, that way I will know who is the owner of the file.

Example: "user asking a question, and attaching a picture to help other users understand the question more easily."

The question values goes into 'questions_table', the file goes to 'files_table', and the user ID also goes to 'files_table'.

The question is! (sorry for the long introduction):
Should I use a pivot table? or just a double one-to-many relation from 1.'users_table' to 'files_table' & 2.from 'question_table' to 'files_table'?

Answer

I think this is the perfect use case for a Polymorphic Relationship.

Here is the structure of the tables:

users
 - id
 - name

questions
 - id
 - title

files
 - id
 - user_id
 - filable_id
 - filable_type

In the files table, you can see a filable_id field that is going to reference either a question id, answer id, comment id. And the filable_type that is going to tell the record which object is associated with this file.

class Question extends Model
{
    /**
     * Get all of the question's files.
     */
    public function files()
    {
        return $this->morphMany('App\File', 'filable');
    }
}

class File extends Model
{
    /**
     * Get all of the owning filable models.
     */
    public function filable()
    {
        return $this->morphTo();
    }
}

I highly encourage you to learn more about this type of relationship on the Laravel Documentation