简体   繁体   English

Laravel 5.3文件表与多个表相关

[英]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'. 问题值进入“ questions_table”,文件进入“ files_table”,用户标识也进入“ 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'? 还是只是从1.'users_table'到'files_table'和2.从'question_table'到'files_table'的一对多关系?

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. files表中,您可以看到一个filable_id字段,该字段将引用问题ID,答案ID,评论ID。 And the filable_type that is going to tell the record which object is associated with this file. filable_type将告诉记录哪个对象与此文件关联。

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 我强烈建议您在Laravel文档中详细了解这种类型的关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM