【问题标题】:Relation to few tables by pivot table通过数据透视表与几个表的关系
【发布时间】:2018-01-10 12:27:58
【问题描述】:

用户可以在帖子中附加文件:图片或视频。

数据库结构如下:

posts
   id
images
   id
videos
   id
post_attachment
   post_id
   attachment_id (id from images or videos table)
   attachment_type ('image' or 'video')

困难在于,根据附件的类型,我们应该参考不同的表格

我应该将 laravel 函数的什么关系应用于Post 模型以通过post_attachment 表获取所有附件?

我认为这种关系是来自一系列的变形,但我无法准确理解是哪一个。

class Post {
     public function attachments () {
        return $this->morph?????
     }
}

请帮我写出这个案例的正确关系。

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    您可能根本不需要数据透视表,例如,您可以使用 hasMany()AttachmentVideo 之间创建关系。或者,为了简化您的数据库结构,我会在 PostAttachment 模型下组织所有内容

    一个例子是:

    class Post extends Model
    {
        public function attachment(){
            return $this->hasMany(Attachment::class);
        }
    }
    

    和你的附件模型:

    class Attachment extends Model
    {
        public function post(){
            return $this->belongsTo(Post::class);
        }
    }
    

    也许在你的桌子上,有一个字段指定允许的不同类型的附件:

    $table->enum('attachment_type', ['video', 'image']);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-22
      • 2014-08-26
      • 2021-01-19
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多