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'])代码>