Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 透视表与少数表的关系_Php_Laravel_Laravel 5 - Fatal编程技术网

Php 透视表与少数表的关系

Php 透视表与少数表的关系,php,laravel,laravel-5,Php,Laravel,Laravel 5,用户可以将文件附加到帖子:图像或视频 数据库的结构如下: posts    id images    id videos    id post_attachment    post_id    attachment_id (id from images or videos table)    attachment_type ('image' or 'video') 困难在于,根据附件的类型,我们应该参考不同的表 我应该对Post模型应用什么样的laravel函数关系才能通过Post\u att

用户可以将文件附加到帖子:图像或视频

数据库的结构如下:

posts
   id
images
   id
videos
   id
post_attachment
   post_id
   attachment_id (id from images or videos table)
   attachment_type ('image' or 'video')
困难在于,根据附件的类型,我们应该参考不同的表

我应该对
Post
模型应用什么样的laravel函数关系才能通过
Post\u attachment
表获得所有附件

我认为这种关系来自一系列变形,但我不能确切地理解是哪一种

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

请帮助我为这种情况编写正确的关系。

您可能根本不需要数据透视表,例如,您可以使用
hasMany()
Attachment
Video
之间创建关系。或者,为了简化数据库结构,我将在
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'])